aboutsummaryrefslogtreecommitdiff
path: root/src/models
diff options
context:
space:
mode:
Diffstat (limited to 'src/models')
-rw-r--r--src/models/base_model.cr5
-rw-r--r--src/models/mixins/.keep0
-rw-r--r--src/models/user.cr13
-rw-r--r--src/models/user_token.cr30
4 files changed, 48 insertions, 0 deletions
diff --git a/src/models/base_model.cr b/src/models/base_model.cr
new file mode 100644
index 0000000..6bafeb8
--- /dev/null
+++ b/src/models/base_model.cr
@@ -0,0 +1,5 @@
+abstract class BaseModel < Avram::Model
+ def self.database : Avram::Database.class
+ AppDatabase
+ end
+end
diff --git a/src/models/mixins/.keep b/src/models/mixins/.keep
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/src/models/mixins/.keep
diff --git a/src/models/user.cr b/src/models/user.cr
new file mode 100644
index 0000000..39729bb
--- /dev/null
+++ b/src/models/user.cr
@@ -0,0 +1,13 @@
+class User < BaseModel
+ include Carbon::Emailable
+ include Authentic::PasswordAuthenticatable
+
+ table do
+ column email : String
+ column encrypted_password : String
+ end
+
+ def emailable : Carbon::Address
+ Carbon::Address.new(email)
+ end
+end
diff --git a/src/models/user_token.cr b/src/models/user_token.cr
new file mode 100644
index 0000000..6586303
--- /dev/null
+++ b/src/models/user_token.cr
@@ -0,0 +1,30 @@
+# Generates and decodes JSON Web Tokens for Authenticating users.
+class UserToken
+ Habitat.create { setting stubbed_token : String? }
+ ALGORITHM = JWT::Algorithm::HS256
+
+ def self.generate(user : User) : String
+ payload = {"user_id" => user.id}
+
+ settings.stubbed_token || create_token(payload)
+ end
+
+ def self.create_token(payload)
+ JWT.encode(payload, Lucky::Server.settings.secret_key_base, ALGORITHM)
+ end
+
+ def self.decode_user_id(token : String) : Int64?
+ payload, _header = JWT.decode(token, Lucky::Server.settings.secret_key_base, ALGORITHM)
+ payload["user_id"].to_s.to_i64
+ rescue e : JWT::Error
+ Lucky::Log.dexter.error { {jwt_decode_error: e.message} }
+ nil
+ end
+
+ # Used in tests to return a fake token to test against.
+ def self.stub_token(token : String, &)
+ temp_config(stubbed_token: token) do
+ yield
+ end
+ end
+end