How to Create a Basic Login System
How to set up a basic login system in your Ask application.
This guide will walk you through setting up and testing an email & password-based JWT login system.
Please make sure that you are familiar with the basics of Ask including the following topics before reading this guide:
Decorators.
Set up
Create a User Database Model.
&basic
db_model User:
id = db.col(db.int, db.pk)
email = db.col(db.str(100), db.unique)
password = db.col(db.str(256))
Create a Signup Route
@post('/user/signup'):
if require_keys(['email', 'password'], body):
status('Missing required parameters', 400)
user_check = db.get_by(email=body['email']).first()
if db.exists(user):
status('Email already registered', 400)
new_user = User(body['email'], hash.hash(body['password']))
db.add(new_user)
respond({
message: 'Success',
user: new_user.s()
})
Create a Login Route
@post('/user/login'):
if require_keys(['email', 'password'], body):
status('Missing required parameters', 400)
user = db.get_by(email=body['email']).first()
if not db.exists(user):
status('Email not registered', 400)
if not hash.check(user.password, body['password']):
status('Wrong password', 400)
# The token will be valid for one hour (3600 seconds).
auth.login(body['email'], 3600)
respond(auth.get_token())
Create a Test Route
&protected
@get('/auth_status'):
respond('You are logged in!')
Try it out
Use .e.g postman to first sign up, and then login. Then make a request to /auth_status
and send the token you received from /login
as a query parameter called token
. If you're using Postman do the following:
Open the
Authorization
tab.Select API key in the
Type
dropdown list.Set
Key
totoken
.Paste in your token into the
Value
field.Select
Query Params
in theAdd To
dropdown list.
You should receive the message "You are logged in!".
Last updated