simplex/models/APIKeys.moon

27 lines
849 B
Plaintext
Raw Normal View History

2018-04-23 12:00:42 +00:00
bcrypt = require "bcrypt"
import Model from require "lapis.db.model"
import encode_base64 from require "lapis.util.encoding"
import autoload from require "locator"
import settings from autoload "utility"
class APIKeys extends Model
2018-04-23 13:13:21 +00:00
@timestamp: true
2018-04-23 12:00:42 +00:00
@primary_key: "user_id"
@table_name: => "api_keys"
@create: (user={}, opts) =>
2018-04-23 13:10:59 +00:00
unless (user.id and user.name and user.digest)
2018-04-23 12:00:42 +00:00
error "API Keys need to be created using a user model."
values = {}
while true
2018-04-23 13:10:59 +00:00
values.user_id = user.id
2018-04-24 22:02:27 +00:00
values.key = encode_base64(bcrypt.digest "#{settings["simplex.key-increment"]}#{user.name}#{user.digest}", settings["users.bcrypt-digest-rounds"])\sub 1, 32
2018-04-23 12:00:42 +00:00
settings["simplex.key-increment"] += 1
unless APIKeys\find key: values.key
2018-04-24 14:00:01 +00:00
settings.save "simplex.key-increment"
2018-04-23 12:00:42 +00:00
break
super values, opts