auth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. package auth
  2. /*
  3. ArOZ Online Authentication Module
  4. author: tobychui
  5. This system make use of sessions (similar to PHP SESSION) to remember the user login.
  6. See https://gowebexamples.com/sessions/ for detail.
  7. Auth database are stored as the following key
  8. auth/login/{username}/passhash => hashed password
  9. auth/login/{username}/permission => permission level
  10. Other system variables related to auth
  11. auth/users/usercount => Number of users in the system
  12. Pre-requirement: imuslab.com/arozos/mod/database
  13. */
  14. import (
  15. "crypto/sha512"
  16. "errors"
  17. "net/http"
  18. "strings"
  19. "sync"
  20. "encoding/hex"
  21. "log"
  22. "time"
  23. "github.com/gorilla/sessions"
  24. "imuslab.com/arozos/mod/auth/accesscontrol/blacklist"
  25. "imuslab.com/arozos/mod/auth/accesscontrol/whitelist"
  26. "imuslab.com/arozos/mod/auth/authlogger"
  27. db "imuslab.com/arozos/mod/database"
  28. )
  29. type AuthAgent struct {
  30. //Session related
  31. SessionName string
  32. SessionStore *sessions.CookieStore
  33. Database *db.Database
  34. LoginRedirectionHandler func(http.ResponseWriter, *http.Request)
  35. //Token related
  36. ExpireTime int64 //Set this to 0 to disable token access
  37. tokenStore sync.Map
  38. terminateTokenListener chan bool
  39. mutex *sync.Mutex
  40. //Autologin Related
  41. AllowAutoLogin bool
  42. autoLoginTokens []*AutoLoginToken
  43. //IPLists manager
  44. WhitelistManager *whitelist.WhiteList
  45. BlacklistManager *blacklist.BlackList
  46. //Logger
  47. Logger *authlogger.Logger
  48. }
  49. type AuthEndpoints struct {
  50. Login string
  51. Logout string
  52. Register string
  53. CheckLoggedIn string
  54. Autologin string
  55. }
  56. //Constructor
  57. func NewAuthenticationAgent(sessionName string, key []byte, sysdb *db.Database, allowReg bool, loginRedirectionHandler func(http.ResponseWriter, *http.Request)) *AuthAgent {
  58. store := sessions.NewCookieStore(key)
  59. err := sysdb.NewTable("auth")
  60. if err != nil {
  61. log.Println("Failed to create auth database. Terminating.")
  62. panic(err)
  63. }
  64. //Creat a ticker to clean out outdated token every 5 minutes
  65. ticker := time.NewTicker(300 * time.Second)
  66. done := make(chan bool)
  67. //Create a new whitelist manager
  68. thisWhitelistManager := whitelist.NewWhitelistManager(sysdb)
  69. //Create a new blacklist manager
  70. thisBlacklistManager := blacklist.NewBlacklistManager(sysdb)
  71. //Create a new logger for logging all login request
  72. newLogger, err := authlogger.NewLogger()
  73. if err != nil {
  74. panic(err)
  75. }
  76. //Create a new AuthAgent object
  77. newAuthAgent := AuthAgent{
  78. SessionName: sessionName,
  79. SessionStore: store,
  80. Database: sysdb,
  81. LoginRedirectionHandler: loginRedirectionHandler,
  82. tokenStore: sync.Map{},
  83. ExpireTime: 120,
  84. terminateTokenListener: done,
  85. mutex: &sync.Mutex{},
  86. //Auto login management
  87. AllowAutoLogin: false,
  88. autoLoginTokens: []*AutoLoginToken{},
  89. //Blacklist management
  90. WhitelistManager: thisWhitelistManager,
  91. BlacklistManager: thisBlacklistManager,
  92. Logger: newLogger,
  93. }
  94. //Create a timer to listen to its token storage
  95. go func(listeningAuthAgent *AuthAgent) {
  96. for {
  97. select {
  98. case <-done:
  99. return
  100. case <-ticker.C:
  101. listeningAuthAgent.ClearTokenStore()
  102. }
  103. }
  104. }(&newAuthAgent)
  105. //Return the authAgent
  106. return &newAuthAgent
  107. }
  108. //Close the authAgent listener
  109. func (a *AuthAgent) Close() {
  110. //Stop the token listening
  111. a.terminateTokenListener <- true
  112. //Close the auth logger database
  113. a.Logger.Close()
  114. }
  115. //This function will handle an http request and redirect to the given login address if not logged in
  116. func (a *AuthAgent) HandleCheckAuth(w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  117. if a.CheckAuth(r) {
  118. //User already logged in
  119. handler(w, r)
  120. } else {
  121. //User not logged in
  122. a.LoginRedirectionHandler(w, r)
  123. }
  124. }
  125. //Handle login request, require POST username and password
  126. func (a *AuthAgent) HandleLogin(w http.ResponseWriter, r *http.Request) {
  127. //Get username from request using POST mode
  128. username, err := mv(r, "username", true)
  129. if err != nil {
  130. //Username not defined
  131. log.Println("[System Auth] Someone trying to login with username: " + username)
  132. //Write to log
  133. a.Logger.LogAuth(r, false)
  134. sendErrorResponse(w, "Username not defined or empty.")
  135. return
  136. }
  137. //Get password from request using POST mode
  138. password, err := mv(r, "password", true)
  139. if err != nil {
  140. //Password not defined
  141. a.Logger.LogAuth(r, false)
  142. sendErrorResponse(w, "Password not defined or empty.")
  143. return
  144. }
  145. //Get rememberme settings
  146. rememberme := false
  147. rmbme, _ := mv(r, "rmbme", true)
  148. if rmbme == "true" {
  149. rememberme = true
  150. }
  151. //Check the database and see if this user is in the database
  152. passwordCorrect, rejectionReason := a.ValidateUsernameAndPasswordWithReason(username, password)
  153. //The database contain this user information. Check its password if it is correct
  154. if passwordCorrect {
  155. //Password correct
  156. //Check if this request origin is allowed to access
  157. ok, reasons := a.ValidateLoginRequest(w, r)
  158. if !ok {
  159. sendErrorResponse(w, reasons.Error())
  160. return
  161. }
  162. // Set user as authenticated
  163. a.LoginUserByRequest(w, r, username, rememberme)
  164. //Print the login message to console
  165. log.Println(username + " logged in.")
  166. a.Logger.LogAuth(r, true)
  167. sendOK(w)
  168. } else {
  169. //Password incorrect
  170. log.Println(username + " login request rejected: " + rejectionReason)
  171. sendErrorResponse(w, rejectionReason)
  172. a.Logger.LogAuth(r, false)
  173. return
  174. }
  175. }
  176. func (a *AuthAgent) ValidateUsernameAndPassword(username string, password string) bool {
  177. succ, _ := a.ValidateUsernameAndPasswordWithReason(username, password)
  178. return succ
  179. }
  180. //validate the username and password, return reasons if the auth failed
  181. func (a *AuthAgent) ValidateUsernameAndPasswordWithReason(username string, password string) (bool, string) {
  182. hashedPassword := Hash(password)
  183. var passwordInDB string
  184. err := a.Database.Read("auth", "passhash/"+username, &passwordInDB)
  185. if err != nil {
  186. //User not found or db exception
  187. //log.Println("[System Auth] " + username + " login with incorrect password")
  188. return false, "Invalid username or password"
  189. }
  190. if passwordInDB == hashedPassword {
  191. return true, ""
  192. } else {
  193. return false, "Invalid username or password"
  194. }
  195. }
  196. //Validate the user request for login
  197. func (a *AuthAgent) ValidateLoginRequest(w http.ResponseWriter, r *http.Request) (bool, error) {
  198. //Check if the account is whitelisted
  199. if a.WhitelistManager.Enabled && !a.WhitelistManager.CheckIsWhitelistedByRequest(r) {
  200. //Whitelist enabled but this IP is not whitelisted
  201. return false, errors.New("Your IP is not whitelisted on this host")
  202. }
  203. //Check if the account is banned
  204. if a.BlacklistManager.Enabled && a.BlacklistManager.CheckIsBannedByRequest(r) {
  205. //This user is banned
  206. return false, errors.New("Your IP is banned by this host")
  207. }
  208. return true, nil
  209. }
  210. //Login the user by creating a valid session for this user
  211. func (a *AuthAgent) LoginUserByRequest(w http.ResponseWriter, r *http.Request, username string, rememberme bool) {
  212. session, _ := a.SessionStore.Get(r, a.SessionName)
  213. session.Values["authenticated"] = true
  214. session.Values["username"] = username
  215. session.Values["rememberMe"] = rememberme
  216. //Check if remember me is clicked. If yes, set the maxage to 1 week.
  217. if rememberme == true {
  218. session.Options = &sessions.Options{
  219. MaxAge: 3600 * 24 * 7, //One week
  220. Path: "/",
  221. }
  222. } else {
  223. session.Options = &sessions.Options{
  224. MaxAge: 3600 * 1, //One hour
  225. Path: "/",
  226. }
  227. }
  228. session.Save(r, w)
  229. }
  230. //Handle logout, reply OK after logged out. WILL NOT DO REDIRECTION
  231. func (a *AuthAgent) HandleLogout(w http.ResponseWriter, r *http.Request) {
  232. username, _ := a.GetUserName(w, r)
  233. if username != "" {
  234. log.Println(username + " logged out.")
  235. }
  236. // Revoke users authentication
  237. err := a.Logout(w, r)
  238. if err != nil {
  239. sendErrorResponse(w, "Logout failed")
  240. return
  241. }
  242. w.Write([]byte("OK"))
  243. }
  244. func (a *AuthAgent) Logout(w http.ResponseWriter, r *http.Request) error {
  245. session, err := a.SessionStore.Get(r, a.SessionName)
  246. if err != nil {
  247. return err
  248. }
  249. session.Values["authenticated"] = false
  250. session.Values["username"] = nil
  251. session.Save(r, w)
  252. return nil
  253. }
  254. //Get the current session username from request
  255. func (a *AuthAgent) GetUserName(w http.ResponseWriter, r *http.Request) (string, error) {
  256. if a.CheckAuth(r) {
  257. //This user has logged in.
  258. session, _ := a.SessionStore.Get(r, a.SessionName)
  259. return session.Values["username"].(string), nil
  260. } else {
  261. //This user has not logged in.
  262. return "", errors.New("User not logged in")
  263. }
  264. }
  265. //Check if the user has logged in, return true / false in JSON
  266. func (a *AuthAgent) CheckLogin(w http.ResponseWriter, r *http.Request) {
  267. if a.CheckAuth(r) != false {
  268. sendJSONResponse(w, "true")
  269. } else {
  270. sendJSONResponse(w, "false")
  271. }
  272. }
  273. //Handle new user register. Require POST username, password, group.
  274. func (a *AuthAgent) HandleRegister(w http.ResponseWriter, r *http.Request) {
  275. userCount := a.GetUserCounts()
  276. //Get username from request
  277. newusername, err := mv(r, "username", true)
  278. if err != nil {
  279. sendTextResponse(w, "Error. Missing 'username' paramter")
  280. return
  281. }
  282. //Get password from request
  283. password, err := mv(r, "password", true)
  284. if err != nil {
  285. sendTextResponse(w, "Error. Missing 'password' paramter")
  286. return
  287. }
  288. //Set permission group to default
  289. group, err := mv(r, "group", true)
  290. if err != nil {
  291. sendTextResponse(w, "Error. Missing 'group' paramter")
  292. return
  293. }
  294. //Check if the number of users in the system is == 0. If yes, there are no need to login before registering new user
  295. if userCount > 0 {
  296. //Require login to create new user
  297. if a.CheckAuth(r) == false {
  298. //System have more than one person and this user is not logged in
  299. sendErrorResponse(w, "Login is needed to create new user")
  300. return
  301. }
  302. }
  303. //Ok to proceed create this user
  304. err = a.CreateUserAccount(newusername, password, []string{group})
  305. if err != nil {
  306. sendErrorResponse(w, err.Error())
  307. return
  308. }
  309. //Return to the client with OK
  310. sendOK(w)
  311. log.Println("[System Auth] New user " + newusername + " added to system.")
  312. return
  313. }
  314. //Check authentication from request header's session value
  315. func (a *AuthAgent) CheckAuth(r *http.Request) bool {
  316. session, _ := a.SessionStore.Get(r, a.SessionName)
  317. // Check if user is authenticated
  318. if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
  319. return false
  320. }
  321. return true
  322. }
  323. //Handle de-register of users. Require POST username.
  324. //THIS FUNCTION WILL NOT CHECK FOR PERMISSION. PLEASE USE WITH PERMISSION HANDLER
  325. func (a *AuthAgent) HandleUnregister(w http.ResponseWriter, r *http.Request) {
  326. //Check if the user is logged in
  327. if a.CheckAuth(r) == false {
  328. //This user has not logged in
  329. sendErrorResponse(w, "Login required to remove user from the system.")
  330. return
  331. }
  332. //Check for permission of this user.
  333. /*
  334. if !system_permission_checkUserIsAdmin(w,r){
  335. //This user is not admin. No permission to access this function
  336. sendErrorResponse(w, "Permission denied")
  337. }
  338. */
  339. //Get username from request
  340. username, err := mv(r, "username", true)
  341. if err != nil {
  342. sendErrorResponse(w, "Missing 'username' paramter")
  343. return
  344. }
  345. err = a.UnregisterUser(username)
  346. if err != nil {
  347. sendErrorResponse(w, err.Error())
  348. return
  349. }
  350. //Return to the client with OK
  351. sendOK(w)
  352. log.Println("[system_auth] User " + username + " has been removed from the system.")
  353. return
  354. }
  355. func (a *AuthAgent) UnregisterUser(username string) error {
  356. //Check if the user exists in the system database.
  357. if !a.Database.KeyExists("auth", "passhash/"+username) {
  358. //This user do not exists.
  359. return errors.New("This user does not exists.")
  360. }
  361. //OK! Remove the user from the database
  362. a.Database.Delete("auth", "passhash/"+username)
  363. a.Database.Delete("auth", "group/"+username)
  364. a.Database.Delete("auth", "acstatus/"+username)
  365. a.Database.Delete("auth", "profilepic/"+username)
  366. //Remove the user's autologin tokens
  367. a.RemoveAutologinTokenByUsername(username)
  368. return nil
  369. }
  370. //Get the number of users in the system
  371. func (a *AuthAgent) GetUserCounts() int {
  372. entries, _ := a.Database.ListTable("auth")
  373. usercount := 0
  374. for _, keypairs := range entries {
  375. if strings.Contains(string(keypairs[0]), "passhash/") {
  376. //This is a user registry
  377. usercount++
  378. }
  379. }
  380. if usercount == 0 {
  381. log.Println("There are no user in the database.")
  382. }
  383. return usercount
  384. }
  385. //List all username within the system
  386. func (a *AuthAgent) ListUsers() []string {
  387. entries, _ := a.Database.ListTable("auth")
  388. results := []string{}
  389. for _, keypairs := range entries {
  390. if strings.Contains(string(keypairs[0]), "group/") {
  391. username := strings.Split(string(keypairs[0]), "/")[1]
  392. results = append(results, username)
  393. }
  394. }
  395. return results
  396. }
  397. //Check if the given username exists
  398. func (a *AuthAgent) UserExists(username string) bool {
  399. userpasswordhash := ""
  400. err := a.Database.Read("auth", "passhash/"+username, &userpasswordhash)
  401. if err != nil || userpasswordhash == "" {
  402. return false
  403. }
  404. return true
  405. }
  406. //Update the session expire time given the request header.
  407. func (a *AuthAgent) UpdateSessionExpireTime(w http.ResponseWriter, r *http.Request) bool {
  408. session, _ := a.SessionStore.Get(r, a.SessionName)
  409. if session.Values["authenticated"].(bool) == true {
  410. //User authenticated. Extend its expire time
  411. rememberme := session.Values["rememberMe"].(bool)
  412. //Extend the session expire time
  413. if rememberme == true {
  414. session.Options = &sessions.Options{
  415. MaxAge: 3600 * 24 * 7, //One week
  416. Path: "/",
  417. }
  418. } else {
  419. session.Options = &sessions.Options{
  420. MaxAge: 3600 * 1, //One hour
  421. Path: "/",
  422. }
  423. }
  424. session.Save(r, w)
  425. return true
  426. } else {
  427. return false
  428. }
  429. }
  430. //Create user account
  431. func (a *AuthAgent) CreateUserAccount(newusername string, password string, group []string) error {
  432. key := newusername
  433. hashedPassword := Hash(password)
  434. err := a.Database.Write("auth", "passhash/"+key, hashedPassword)
  435. if err != nil {
  436. return err
  437. }
  438. //Store this user's usergroup settings
  439. err = a.Database.Write("auth", "group/"+newusername, group)
  440. if err != nil {
  441. return err
  442. }
  443. return nil
  444. }
  445. //Hash the given raw string into sha512 hash
  446. func Hash(raw string) string {
  447. h := sha512.New()
  448. h.Write([]byte(raw))
  449. return hex.EncodeToString(h.Sum(nil))
  450. }