Electron browserWindow password prompt - electron

I have a simple electron app that wraps around a web app. The web app prompts for user name but electron doesn't show the prompt and directly goes to the 401 Authorization Required page. Is there a setting I need to change to make the prompt show? I can't seem to find it in the documentation. Any help is appreciated.
const { app, BrowserWindow } = require('electron');
function createWindow() {
browserWindow = new BrowserWindow({});
browserWindow.loadURL('https://domain')
}
app.on('ready', createWindow);

Listen to this "login" event.
Create your own prompt. For example, create a browser window which loads an HTML form and when the user fills the username and password fields pass the credentials back via ipc calls to the callback.
app.on("login", (event, webContents, request, authInfo, callback) => {
event.preventDefault();
createAuthPrompt().then(credentials => {
callback(credentials.username, credentials.password);
});
});
function createAuthPrompt() {
const authPromptWin = new BrowserWindow();
authPromptWin.loadFile("auth-form.html"); // load your html form
return new Promise((resolve, reject) => {
ipcMain.once("form-submission", (event, username, password) => {
authPromptWin.close();
const credentials = {
username,
password
};
resolve(credentials);
});
});
}

Related

NextAuth.js callbackUrl and first attempt after sign in

I am implementing NextAuth authentication and there is something that remains unclear for me. I explain.
To perform authentication with CredentialsProviders and signIn() well (means avoid the session's status unauthenticated during the first attempt). The doc gives a partial solution which is:
You can use useSession() in a way that makes sure you always have a valid session
I use the default behavior to satisfy this advice by implementing my signIn() method like this
const login_user = async () => {
const response = await signIn("Credentials", {
redirect: false,
username: username,
password: password,
});
if (response?.error) {
setError(response.error);
} else {
setError(null);
}
//If user signed successfully we redirect to the dashboard page
if (response.url && response.ok === true) {
router.push("/dashboard/general");
}
};
and it works well.
Now always in the doc, they say that we may add callbackUrl to signIn() which is the url where you want to redirect the user after successful sign in.
I configure my redirect callback in [...nextauth].ts file like this
redirect: async ({ url, baseUrl }) => {
return url.startsWith(baseUrl)
? Promise.resolve(url)
: Promise.resolve(baseUrl);
},
and modify signIn() method by adding it callbackUrl like below in the react component.
const login_user = async () => {
const response = await signIn("Credentials", {
redirect: false,
username: username,
password: password,
callbackUrl: "/dashboard/general",
});
if (response?.error) {
setError(response.error);
} else {
setError(null);
}
};
But when a user sign in, he is not redirected.
My question is:
What is the role of callbackUrl at that place if after the sign in or first attempt of sign in it cannot redirect the user to the specified callbackUrl?
I know the importance of callbackUrl about security against attacker)
May be I do not understand well that notion.
Can someone explains it?

Is it possible to create modular tests with playwright?

I'm trying to make tests for a webapplication with Playwright test in JavaScript, but I would like to make them modular, to avoid repeating code. Let's say two tests need to fill a form. Instead of writing code to fill the form in both tests, is it possible to include a file in these two tests that contains filling the form?
import { test, expect } from '#playwright/test';
test.describe("", () => {
//create a new page
test.beforeAll( async ({ browser }) => {
let page = await browser.newPage();
await page.goto('https://www.example.com/');
})
test('Do stuff', async () => {
import{test} from 'login.spec.mjs';
import{test} from 'fillform.spec.mjs';
})
login.spec.mjs
test('Login', async () => {
// Click input[name="username"]
await page.click('input[name="username"]');
//...
})
How do we call these functions, which are all named "test()"? Is this a good way to approach testing?
You can create a function called login() that does takes in parameters that will fill out the form.
For instance, you can do the following:
import { test, expect } from '#playwright/test';
function loginForm(page, input1, input2) {
await page.goto('URL NAME HERE');
await page.fill('#inputID1', input1);
await page.fill('#inputID2', input2);
await page.click('#loginButton');
}
test('Test Login for User 1', async ({page}) => {
loginForm(page, 'username1', 'password1');
// Do more stuff here
}
test('Test Login for User 2', async ({page}) => {
await loginForm(page, 'username2', 'password2');
// Do more stuff here
}
test('Test Login for User 3', async ({page}) => {
await loginForm(page, 'username3', 'password3');
// Do more stuff here
}

Rails/Redux/Devise - Trying to log in user but along the way the value of currentUser becomes HTML string of the document

I'm working on a Rails/React/Redux app using Devise for user authentication. There's something fishy going on somewhere in between my login function and my receiveCurrentUser action where the currentUser becomes changed to an HTML string of the entire document. Here's what happens:
I first dispatch this login function:
export const login = (user) => (dispatch) => {
debugger
return SessionAPIUtil.login(user)
.then(currentUser => {
dispatch(receiveCurrentUser(currentUser));
return currentUser;
},
errors => {
dispatch(receiveSessionErrors(errors.responseJSON));
return errors;
});
};
Putting in a debugger I saw that my user was what it should be:
{username: "test_user", password: "password123"}
A debugger in my login util function (ajax call) still has user as what it should be.
export const login = user => {
debugger
return $.ajax({
method: 'POST',
url: '/users/sign_in',
data: { user }
});
};
However, when it returns from the ajax call to the ".then(..." of the first login function and we enter the receiveCurrentUser:
export const receiveCurrentUser = (currentUser) => {
debugger
return {
type: RECEIVE_CURRENT_USER,
currentUser
};
};
a debugger reveals that currentUser is an HTML string of the document:
Any insight or advice would be greatly appreciated!

Google OAuth Issue

I have a Umbraco website that has google sign in button configured as follows:
At the top of the page (inside the header section) I have the scripts for calling google API:
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: '<myapp client Id>.apps.googleusercontent.com',
// Scopes to request in addition to 'profile' and 'email'
redirect_uri: 'http://localhost:40136/umbraco/Surface/AuthSurface/GoogleAuthrizedUser',
scope: 'profile email'
});
});
}
</script>
In the body section of the code I have the google button setup and associated click function:
<script>
function onSignIn(authResult) {
if (authResult['code']) {
var authCode = authResult['code'];
console.log("Authorization Code: " + authCode);
$.post("/umbraco/Surface/AuthSurface/GoogleAuthrizedUser", { code: authCode })
.done(function(msg) {
// Success settings
})
.fail(function(xhr, status, error) {
});
} else {
//authResult['code'] is null
//handle the error message.
}
};
</script>
Controller code that handles the call back on the server end:
public class AuthSurfaceController : SurfaceController
{
public ActionResult GoogleAuthrizedUser()
{
string AuthCode = HttpContext.Request["code"];
var info = new GoogleAccessTokenResponse();
var client = new GoogleOAuthClient();
try
{
info = client.GetAccessTokenFromAuthorizationCode(AuthCode);
}
catch (Exception ex)
{
var strMessage = String.Format("<div class=\"info\"><p>{0}</p><p>{1}</p></div>", "Google Login Error",
ex.Message);
return Json(new AjaxOperationResponse(false, strMessage));
}
}
}
On the Serverside I am using Skybrud Social plugin for accessing google apis.
The google authentication happens in the popup and authorizes client with credentials and authResult['code'] has a valid code.
In the controller when I initialize the client and call the function GetAccessTokenFromAuthorizationCode(AuthCode), it returns an exception of 'Invalid Request'
I tried checking this authResult['code'] returned in the javascript function onSignIn in the https://developers.google.com/oauthplayground/
Same error description is shown 'Invalid request'. I am not sure why this is happening. The error returned is "invalid_grant"
Can anyone have a solution to this problem? What am I doing wrong here?
In your surface controller you're initializing a new instance of GoogleOAuthClient, but without setting any of the properties. The GetAccessTokenFromAuthorizationCode method requires the ClientId, ClientSecret and RedirectUri properties to have a value. You can initialize the properties like this:
// Initialize a new instance of the OAuth client
GoogleOAuthClient oauth = new GoogleOAuthClient {
ClientId = "The client ID of your project",
ClientSecret = "The client secret of your project",
RedirectUri = "The return URI (where users should be redirected after the login)"
};
You can read more about authentication in the documentation: http://social.skybrud.dk/google/authentication/ (the approach explained there will however not use any JavaScript)

How to Login through AJAX in ASP.NET MVC 3

No i have been stuck here ... can you please help me out...
$(':submit').click(function (e) {
var username = $('#username').val();
var password = $('#password').val();
var postdata =
{
'Email': username,
'Password': password
};
$.post({
url: 'http://localhost:7651/Home/CheckLogin',
data: postdata,
success: function (msg) {
alert('Hi');
}
});
});
this is not working ...its not calling the action controller somehow...
my controller action is
public string CheckLogin(Users checkuser)
{
if (db.CheckUserLoginDetails(checkuser.Email, checkuser.Password))
{
return "Login Successful:" + checkuser.Email;
}
else
{
return "Login UnSuccessful";
}
}
please help.... also do i need to prevent the defualt behavior of the submit button like e.preventDefault();
Here are the steps you need to do:
Your LoginController would need to validate the login and return the HTML Fragments containing the Login Status. Note that you don't need a fullblown HTML here. Just the fragments containing the result
As you probably know, you can utilize jQuery.ajax that you put in your view. To append the Login Result into the DIV, you could use jQuery.html Here is the snippet that you would need (NOTE: not debugged yet, but roughly something like below)
// Override form submit
$("form").live("submit", function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
// Get the action URL
url: form.attr('action'),
type: "POST",
// get all form variables
data: form.serialize(),
// upon success, the fragment of HTML from the Controller will be stored in loginResultHtml
success: function(loginResultHtml){
// append the html to your login DIV id using jQuery.html function
$(#your-login-status-div-id).html(loginResultHtml);
}
});
});

Resources