12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- 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
- [console: "/console/#{config.secret}"]: =>
- if Users\count! < 1 or @session.id == 1
- return console.make(env: "all")(@)
- else
- return status: 401, "401 - Unauthorized"
-
- [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."
- }
|