aboutsummaryrefslogtreecommitdiff
path: root/src/guff/models
diff options
context:
space:
mode:
authorPaul Duncan <pabs@pablotron.org>2016-03-31 21:21:05 -0400
committerPaul Duncan <pabs@pablotron.org>2016-03-31 21:21:05 -0400
commitec78a9b0fed0d54d6cc6695f80484e34286921ab (patch)
tree97e1bffa8beb75cc385130308630f19614ab389d /src/guff/models
parenteb28614ecc82220db2c1bb7991f05f0f1ff46958 (diff)
downloadold-guff-ec78a9b0fed0d54d6cc6695f80484e34286921ab.tar.bz2
old-guff-ec78a9b0fed0d54d6cc6695f80484e34286921ab.zip
add user models
Diffstat (limited to 'src/guff/models')
-rw-r--r--src/guff/models/user.cr88
1 files changed, 88 insertions, 0 deletions
diff --git a/src/guff/models/user.cr b/src/guff/models/user.cr
new file mode 100644
index 0000000..4dc6d0a
--- /dev/null
+++ b/src/guff/models/user.cr
@@ -0,0 +1,88 @@
+class Guff::UserModel < Guff::Model
+ SQL = TemplateCache.new({
+ add_user: "
+ INSERT INTO users(user_name) VALUES (:user_name)
+ ",
+
+ update_user: "
+ UPDATE users
+ SET %{sets}
+ WHERE user_id = :user_id
+ ",
+
+ delete_login: "
+ DELETE FROM user_logins WHERE user_id = :user_id
+ ",
+
+ add_login: "
+ INSERT INTO user_logins(user_id, email, pass_hash) VALUES
+ (:user_id, :email, :pass_hash)
+ ",
+ })
+
+ def initialize(models : Models)
+ super(models, SQL)
+ end
+
+ def add_user(user_name : String)
+ query(:add_user, {
+ "user_name": user_name
+ }, nil)
+
+ # return user id
+ last_insert_row_id
+ end
+
+ def update_user(
+ user_id : Int32,
+ user_name : String? = nil,
+ active : Boolean? = nil,
+ )
+ sets = [] of String
+ args = { "user_id": user_id.to_s }
+
+ if user_name != nil
+ sets << "user_name = :user_name"
+ args["user_name"] = user_name
+ end
+
+ if active != nil
+ sets << "is_active = :is_active"
+ args["is_active"] = active ? "1" : "0"
+ end
+
+ query(:update_user, args, {
+ "sets": sets.join(","),
+ }) if sets.length > 0
+ end
+
+ def delete_login(user_id : Int32)
+ query(:delete_login, {
+ "user_id": user_id.to_s
+ }, nil)
+ end
+
+ def add_login(
+ user_id : Int32,
+ email : String,
+ password : String,
+ )
+ # TODO: check password strength
+ raise "password too short" if password.length < 4
+
+ # hash password
+ pass_hash = Crypto::Bcrypt::Password.create(password, cost: 10)
+
+ transaction do
+ # clear old credentials
+ delete_login(user_id)
+
+ # add new credentials
+ query(:add_login, {
+ "user_id": user_id.to_s,
+ "email": email,
+ "pass_hash": pass_hash,
+ }, nil)
+ end
+ end
+end