From 6b9ca27c67d043a8737da652bf7915645628db4c Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Fri, 1 Apr 2016 15:58:08 -0400 Subject: add_user test --- src/guff/models/user.cr | 56 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 12 deletions(-) (limited to 'src/guff/models') diff --git a/src/guff/models/user.cr b/src/guff/models/user.cr index 1862e29..98ae10b 100644 --- a/src/guff/models/user.cr +++ b/src/guff/models/user.cr @@ -1,3 +1,5 @@ +require "crypto/bcrypt" + class Guff::UserModel < Guff::Model SQL = TemplateCache.new({ add_user: " @@ -34,17 +36,47 @@ class Guff::UserModel < Guff::Model r end - def add_user(name : String) - query(:add_user, { - "user_name": name - }, nil) + def add_user( + name : String, + active : Bool? = nil, + role : String? = nil, + email : String? = nil, + password : String? = nil, + ) + user_id = -1_i64 + + transaction do + # add user + query(:add_user, { + "user_name": name + }, nil) + + # get user_id + user_id = last_insert_row_id as Int64 + + # set active and/or role + if active || role + update_user(user_id, + active: active, + role: role, + ) + end + + # add login + if email || password + add_login(user_id, + email.not_nil!, + password.not_nil! + ) + end + end - # return user id - last_insert_row_id + # return id + user_id end def update_user( - user_id : Int32, + user_id : Int64, name : String? = nil, active : Bool? = nil, role : String? = nil, @@ -63,7 +95,7 @@ class Guff::UserModel < Guff::Model end if role != nil - args["role_name"] = role.not_nil! + args["role"] = role.not_nil! sets << " role_id = (SELECT role_id FROM roles @@ -77,22 +109,22 @@ class Guff::UserModel < Guff::Model }) if sets.size > 0 end - def delete_login(user_id : Int32) + def delete_login(user_id : Int64) query(:delete_login, { "user_id": user_id.to_s }, nil) end def add_login( - user_id : Int32, + user_id : Int64, email : String, password : String, ) # TODO: check password strength - raise "password too short" if password.length < 4 + raise "password too short" if password.size < 4 # hash password - pass_hash = Crypto::Bcrypt::Password.create(password, cost: 10) + pass_hash = Crypto::Bcrypt::Password.create(password, cost: 10).to_s transaction do # clear old credentials -- cgit v1.2.3