aboutsummaryrefslogtreecommitdiff
path: root/src/models/user_token.cr
diff options
context:
space:
mode:
Diffstat (limited to 'src/models/user_token.cr')
-rw-r--r--src/models/user_token.cr30
1 files changed, 30 insertions, 0 deletions
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