simplex/models/APIKeys.moon
2018-04-24 15:02:27 -07:00

27 lines
849 B
Plaintext

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
@timestamp: true
@primary_key: "user_id"
@table_name: => "api_keys"
@create: (user={}, opts) =>
unless (user.id and user.name and user.digest)
error "API Keys need to be created using a user model."
values = {}
while true
values.user_id = user.id
values.key = encode_base64(bcrypt.digest "#{settings["simplex.key-increment"]}#{user.name}#{user.digest}", settings["users.bcrypt-digest-rounds"])\sub 1, 32
settings["simplex.key-increment"] += 1
unless APIKeys\find key: values.key
settings.save "simplex.key-increment"
break
super values, opts