1
Good night, you guys! I have tried 3 different ways, but the closest I got was the code I will post below, I am developing an application as a study using Angular and Python and currently I already validate my user without using token, now I’m trying to deploy but I can’t insert the token in my browser.
Follows snippets of code:
My backend in Python:
class Login(Resource):
def post(self):
parser.add_argument('username', type=str)
parser.add_argument('password', type=str)
args = parser.parse_args()
password = hashlib.md5(args['password'].encode('utf-8')).hexdigest()
sql = "SELECT * FROM usuarios WHERE username = (%s) and password = (%s)"
value = (args['username'], password)
dbcursor.execute(sql, value)
result = dbcursor.fetchall()
if len(result) > 0:
return {"message": "user valido"}
id_user = result[0][0]
payload = {"id": id_user}
token = jwt.encode(payload, config.JWT.secret, algorithm='HS256')
data = json.dumps({"id": id_user, "username": result[0][1], "token": token.decode("UTF-8)")})
res = Response(str(data),mimetype='application/json')
res.headers['x-access-token'] = "JWT"+token.decode("UTF-8")
else:
return {"message": "user invalido"}
def get(self):
token = request.cookies.get("JWT")
if not token:
return {"message": "Faca login na aplicacao primeiro"}
token = jwt.decode(token, config.JWT.secret, algorithm='HS2556')
sql = "SELECT * FROM usuarios where id = (%s)"
value = (str(token["id"]),)
dbcursor.execute(sql, value)
result = dbcursor.fetchall()
return result
My service using Angular:
authenticate(username: string, password: string) {
return this.http
.post(
API_URL,
{ "username":username, "password":password },
{ observe: 'response' } )
.pipe(tap(res => {
const authToken = res.headers.get('x-access-token')
console.log(authToken)
}))
}
My component with Angular:
userLogin(){
const username = this.loginForm.get('username').value;
const password = this.loginForm.get('password').value;
this.authService
.authenticate(username, password)
.subscribe((res) => {
if (res ["message"] == 'user valido') {
this.router.navigate(['dashboard'])
}
else {
console.log('Caiu no else')
this.loginForm.reset()
this.platformDetectorService.isPlatformBrower() &&
this.usernameInput.nativeElement.focus()
}
}
)}
This way it ends up not validating my user (drops into Else), prints my authToken as null and does not register the token in the browser, some north or hint ? Thank you :)
I don’t know Python, but the line
return {"message": "user valido"}
should not be in the line before theelse
? After making the request to the server, save the token somewhere (Sessiontoken, Localstorage or Cookie, can be saved to a variable, but it is a bit rough)– Costamilam
Precisely, you put the
return {"message": "user valido"}
at the very beginning of the block and the execution ends at this point and does not end the authentication process.– Giovanni Nunes
Oops, so, I already took it out too and it still doesn’t work, brother. The token print on my angular component is still null, first I’d like to print it, then q I’m really picking it up I’ll store it on the localStorage
– Fernando Munhoz