Skip to content

Commit 1b87317

Browse files
committed
Add login API.
1 parent 4e1b285 commit 1b87317

3 files changed

Lines changed: 26 additions & 5 deletions

File tree

project.clj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
[clj-liquibase "0.5.2"]
55
[com.h2database/h2 "1.3.173"]
66
[crypto-password "0.1.3"]
7+
[crypto-random "1.2.0"]
78
[log4j/log4j "1.2.17"]
89
[metosin/ring-swagger "0.13.0"]
910
[metosin/compojure-api "0.16.0"]

src/hyperspace/server/database/migrations.clj

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
[(ch/create-table :users
88
[[:id :int :null false :pk true :autoinc true]
99
[:login [:varchar 128] :unique true :null false]
10-
[:password [:varchar 128] :null false]])
10+
[:password [:varchar 128] :null false]
11+
[:session [:varchar 16] :null true :unique true]])
1112
(ch/create-index :users [:login])]])
1213

1314
(defchangelog changelog "hyperspace-server" [add-users-table])
Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,32 @@
11
(ns hyperspace.server.database.user
2-
(:require [crypto.password.scrypt :as password])
3-
(:use [azql.core :only [select from insert! values]]
2+
(:import (java.util UUID))
3+
(:require [crypto.password.scrypt :as password]
4+
[crypto.random :as random])
5+
(:use [azql.core]
46
[hyperspace.server.database.datasource :only [db-spec]]))
57

68
(defn create [{login :login password :password}]
79
(insert! db-spec :users
810
(values [{:login login
911
:password (password/encrypt password)}])))
1012

13+
(defn- generate-session []
14+
;; 8 random bytes = 16 hex digits should be enough for duplicates to be almost impossible with probability of about
15+
;; 10^-12
16+
(random/hex 8))
17+
1118
(defn login [{login :login password :password}]
12-
;; TODO: log in and save session
13-
nil)
19+
(with-connection [c db-spec]
20+
(transaction c
21+
(let [user (fetch-one c
22+
(select (fields [:login :password])
23+
(from :u :users)
24+
(where (= :u.login login))))
25+
user-id (:id user)]
26+
(if (password/check password (:password user))
27+
(let [session (generate-session)]
28+
(update! c :users
29+
(setf :session session)
30+
(where (= :id user-id)))
31+
session)
32+
nil)))))

0 commit comments

Comments
 (0)