crystal-gauntlet/src/endpoints/accounts/registerAccount.cr

36 lines
1.2 KiB
Crystal
Raw Normal View History

2022-12-30 17:04:27 +01:00
require "uri"
require "base64"
require "crypto/bcrypt/password"
include CrystalGauntlet
CrystalGauntlet.endpoints["/accounts/registerGJAccount.php"] = ->(body : String): String {
params = URI::Params.parse(body)
2023-01-02 11:59:37 +01:00
LOG.debug { params.inspect }
2022-12-30 17:04:27 +01:00
2022-12-31 09:16:43 +01:00
if config_get("accounts.allow_registration").as(Bool | Nil) == false
return "-1"
end
2022-12-31 20:05:39 +01:00
username = Clean.clean_basic(params["userName"])
2022-12-30 17:04:27 +01:00
password = params["password"]
email = params["email"]
# caps checks aren't required because `username` is already COLLATE NOCASE in the db
2022-12-30 17:04:27 +01:00
username_exists = DATABASE.scalar "select count(*) from accounts where username = ?", username
if username_exists != 0
return "-2"
end
2022-12-31 03:13:29 +01:00
# todo: email checks, conditionally?
2022-12-30 17:04:27 +01:00
password_hash = Crypto::Bcrypt::Password.create(password, cost: 10).to_s
gjp2 = CrystalGauntlet::GJP.hash(password)
next_id = IDs.get_next_id("accounts")
2022-12-30 17:04:27 +01:00
DATABASE.exec "insert into accounts (id, username, password, email, gjp2) values (?, ?, ?, ?, ?)", next_id, username, password_hash, email, gjp2
user_id = IDs.get_next_id("users")
2022-12-30 17:04:27 +01:00
DATABASE.exec "insert into users (id, account_id, username, registered) values (?, ?, ?, 1)", user_id, next_id, username
"1"
}