lapis = require "lapis" bcrypt = require "bcrypt" config = require("lapis.config").get! import Users from require "models" import api, abort, assert_model from require "helpers" class extends lapis.Application [authenticate: "/0/auth"]: api { POST: => -- 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 "No such user." 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 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 -- TODO passwords should be required to follow a few other basic security checks -- actually, these are invalidated just by checking against breached passwords I think 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 } [name: "/0/:id[%d]"]: api { GET: => if user = Users\find id: @params.id return name: user.name else abort "No such user." }