in my django project, i have a url that has login_required set, because i need the request.user variable in it to process some data,
i also created a simple chrome extension where i'm going to have to send requests to that django project url.
i do not want to use the username and password in the extension to login and send the request
i want to:
redirect the user when the extension is installed to the my website
they will login,
the extension will know that the user has logged in and it will get (and save) a key that i could maybe inject in the page after login is successful
the key can be used as a query parameter in the request in order to identify the user without any username and password
i'm sorry if this seems as a stupid question, but i'm very confused on how to do this
PS: i have already a system in place where the user can use a key in order to make requests without logging in,
i just need a way to open a tab when the extension is installed, and login then get the key (which is injected in the page after login), and save it to use it in the extension later.
When the extension is opened for the first time, I'm showing the user a login page. The login page sends the username & password to an API where they are authenticated. If the information is correct, the required user info is returned (mainly the API key). The information is then saved to local storage.
var username = document.querySelector('[name="username"]');
var password = document.querySelector('[name="password"]');
$.ajax({
URL : 'https://example.com/api/extension-auth/',
type: 'POST',
crossDomain: true,
data: JSON.stringify({
'username': username.value.trim(),
'password': password.value.trim(),
}),
success: res => {
if (res.api_key) {
browser.storage.sync.set({ 'user_data': {'api_key': api_key} }, () => {
// show extension main logged in page
});
}
else {
// show invalid login information alert
}
},
error: function (err) {
// show server error aler
},
});
Everytime the extension is opened the local storage is checked
browser.storage.sync.get('user_data', data => {
if (data.user_data) {
if (valid_api_key(data.user_data.api_key)) {
// show extension main logged in page
}
else {
// show login page
}
}
else {
// show login page
}
});
the valid_api_key function makes a random call to the API to check if there is not an authentication error.
Then, I use the saved API key from local storage to do API requests.
Related
First of all, I am pretty new to working with Rest APIs and tokens, I have learned the basics of Django and React and I've kinda made some projects using those, so I'm giving a shot at making a website with both of them.
Since, registering is simple with django-rest-auth, it's been handled with just POSTING the user data. However, when making a login, the token was returned and I simply do not know how to handle it. I have searched many articles about tokens, but they were all about JWT which returns an access token and a refresh token. However, django-rest-auth returns a single token and I saved it inside a cookie using a 'universal-cookie' in React. Since I'm making an e-commerce website, and I do want to add some functionality to the website by enabling the users to change their email, last name, first name and username, I do need to know the username of the account as it is unique.
So, I am wondering if it would be alright and a good practice to save the username inside a cookie, again using a universal-cookie. It'd also be appreciated if someone shows me a good article about "what to do with a token" or how to utilize it because I have little to none knowledge about it.
const handleLogin = async (e) => {
e.preventDefault();
const csrftoken = getCookie("csrf");
const url = "http://localhost:8000/rest-auth/login/";
const cookies = new Cookies();
await fetch(url, {
method: "POST",
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
password: password,
}),
}).then((response) => {
setResponseCode(response.status);
response.json().then((key) => {
cookies.set("token", key.key);
setIsClicked(true);
});
});
};`
Here is how I've been storing the token I get, and using it from navbar or other react components to check if the user has been logged in or not.
I'm trying to implement session based authentication the first time using React and Django Rest Framework, but there's some weird thing I don't understand.
I have a pretty standard Login view, so I send POST request from React with username and password, I got response with status 200 and I can see cookies in the response with Chrome developer tools.
But these cookies aren't being saved.If I do the same POST request with Rest plugin for Chrome - it saves them.
Am missing something here since it's my first time? Or should I save it manually somehow?
Here's my request with axios. Do I need to add something here?
const sendLogin = () => {
if (login && password) {
axios.post(SERVER_ADDRESS + 'login/', {username: login, password: password})
.then(response => {
if (response.status !== 200) {
handleClick();
}
else {
history.push('/');
}
})
}
}
I'm trying to implement auth via link without password. E.g. user enter his email -> cognito send an email with link that user can click and login. It
It is supported by cognito via custom challenge. E.g. https://aws-amplify.github.io/amplify-js/media/authentication_guide#using-a-custom-challenge
I have created DefineAuthChallenge, CreateAuthChallenge, VerifyAuthChallenge lambda function that associated with my cognito pool. CreateAuthChallenge generate code that is send to user email with link to site.
Next i was planning to grab that code from url on site and login user via it like its in docs
Auth.signIn(username)
.then(user => {
if (user.challengeName === 'CUSTOM_CHALLENGE') {
Auth.sendCustomChallengeAnswer(user, challengeResponse)
.then(user => console.log(user))
.catch(err => console.log(err));
} else {
console.log(user);
}
})
.catch(err => console.log(err));
But here is the problem. Auth.sendCustomChallengeAnswer require user object that is passed from Auth.signIn. But if user just click link from email there wont be any user object at all. And amplify lib dont save that middle session user object, so on page reload its lost. It is saving only if auth completed to its storage https://github.com/aws-amplify/amplify-js/blob/master/packages/amazon-cognito-identity-js/src/CognitoUser.js#L175
So the question is how can i save & reconstruct user object from Auth.signIn function on page reload. Or if there a better approach to sign in via link without password?
To solve this first you need to save username and session into localstorage or cookies. Then when user go through link this code can be used:
const userPoolData = {
UserPoolId: process.env.COGNITO_POOL_ID,
ClientId: process.env.COGNITO_POOL_WEB_CLIENT_ID,
Storage: customStorageClass // default is localstorage
}
const userPool = new CognitoUserPool(userPoolData)
const userData = {
Username: getUsernameFromCookiesOrLocalstorage,
Pool: userPool,
Storage: customStorageClass // default is localstorage
}
const user = new CognitoUser(userData)
user.Session = getSessionFromCookiesOrLocalstorage
Auth.sendCustomChallengeAnswer(user, code)
I'm busy implementing Facebook login for my django site. I'm not sure if I'm on the right track or way off the ball at the moment. I have implemented the full code as seen in the FB doc example https://developers.facebook.com/docs/facebook-login/web. Basically inserted script on the template. I have the button and once logging in I have the "Welcome fetching your information" "successful login for Joshua Raphael" in my console.log.
How do I now obtain the required email, username and profile pic? Is it a part of the response object? Also if I have email login, is it possible to obtain the response email and check my current database to see if the user is already registered?
Prefer not to use pre-made django apps but if you highly recommend one I may try it.Thanks
I assume you are doing this:
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
you can console.log the response and see what all it contains, you will get the email, username and profilepic in it, also you can specify the fields if it is not there like this:
FB.api('/me', {fields: 'last_name'}, function(response) {
console.log(response);
});
more here
also make sure you have added email in the scope in login method. like this:
FB.login(function(response) {
// handle the response
}, {scope: 'public_profile,email'});
I am not familiar with using Facebook Javascript SDK.
My story is when I access to the website It displays all my friends(pic and name) on a webpage.
I registered Facebook API and App ID
I put website URL as http://localhost:81/ because I am testing my own local machine.
Do you have any good example website or good examples?
Please share with me
Thank you.
First your app should use required permissions like,
user_birthday, friends_birthday, user_location , friends_location...
( for more permissions)
Get info about current user:
FB.api('/me', function(response) {
// Stuff here
});
Get info about current user's friends:
FB.api('/me/friends', function(response) {
// Stuff here
});
you will get the response like,
{data: [{id: "FRIEND1_ID", name: "FRIEND1_NAME"}, {id: "FRIEND2_ID", name: "FRIEND2_NAME"}]....}
If you want get some more properties of your friends, use FIELDS parameter, like
FB.api('/me/friends', {fields: 'name,id,location,birthday'}, function(response) {
// Stuff here
});
If want to get individual user's friend info:
FB.api('/FRIEND1_ID', function(response) {
// Stuff here
});
Try this Example Site
Direct Access Method:
Log into Facebook under your name. If you need an "Access Token", Click on the Extended Permissions and click the "read_friendlist" check box to get your Access Token and then
submit your query. You may need to "Allow" access, so just follow the prompts given.
Voila! You now have the usernames for everyone on your Friends List. The "username" parameter in the query will give you the contact email "message to that person" and you append #facebook.com and send them a message. Very simple.
http://developers.facebook.com/tools/explorer?fql=SELECT%20username%20FROM%20user%20WHERE%20uid%20IN%20%28SELECT%20uid2%20FROM%20friend%20WHERE%20uid1%20%3D%20me%28%29%29%20ORDER%20BY%20name
-SAB