passwd0/app.moon
2018-09-16 12:04:52 -07:00

52 lines
1.7 KiB
Plaintext

lapis = require "lapis"
bcrypt = require "bcrypt"
import Users from require "models"
import api, abort, assert_model from require "helpers"
class extends lapis.Application
-- finds user by name or id (or creates by name), and returns the user,
-- unless a password is not specified (or incorrect), or the password is too weak
[authenticate: "/0/auth"]: respond_to {
POST: api( =>
-- find user by name or id if specified
local user
if @params.name
user = Users\find name: @params.name
elseif @params.id
user = Users\find id: @params.id
abort "Incorrect user name, id, or password." unless user
-- if a user by that name exists, see if the password is correct
if user
unless bcrypt.verify(@params.password, user.digest)
abort "Incorrect user name, id, or password."
-- else create a user
elseif @params.password
assert_valid(@params, {
{ "name", exists: true, min_length: 1, max_length: 255, matches_pattern: "%w+" }
{ "password", exists: true, min_length: 8, max_length: 255 }
})
-- TODO passwords should be checked against known breached passwords
user = assert_model Users\create {
name: @params.name
digest: bcrypt.digest(@params.password, config.digest_rounds)
}
-- if a password wasn't specified...
else
abort "Must specify name or id, and password."
return name: user.name, id: user.id
)
}
-- finds user by id and returns their name
[name: "/0/:id[%d]"]: {
GET: api(=>
if user = Users\find id: @params.id
return name: user.name
else
abort "Incorrect user id."
)
}