auth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. package auth
  2. /*
  3. author: tobychui
  4. */
  5. import (
  6. "crypto/rand"
  7. "crypto/sha512"
  8. "errors"
  9. "fmt"
  10. "net/http"
  11. "net/mail"
  12. "strings"
  13. "encoding/hex"
  14. "github.com/gorilla/sessions"
  15. db "imuslab.com/zoraxy/mod/database"
  16. "imuslab.com/zoraxy/mod/info/logger"
  17. "imuslab.com/zoraxy/mod/utils"
  18. )
  19. type AuthAgent struct {
  20. //Session related
  21. SessionName string
  22. SessionStore *sessions.CookieStore
  23. Database *db.Database
  24. LoginRedirectionHandler func(http.ResponseWriter, *http.Request)
  25. Logger *logger.Logger
  26. }
  27. type AuthEndpoints struct {
  28. Login string
  29. Logout string
  30. Register string
  31. CheckLoggedIn string
  32. Autologin string
  33. }
  34. // Constructor
  35. func NewAuthenticationAgent(sessionName string, key []byte, sysdb *db.Database, allowReg bool, systemLogger *logger.Logger, loginRedirectionHandler func(http.ResponseWriter, *http.Request)) *AuthAgent {
  36. store := sessions.NewCookieStore(key)
  37. err := sysdb.NewTable("auth")
  38. if err != nil {
  39. systemLogger.Println("Failed to create auth database. Terminating.")
  40. panic(err)
  41. }
  42. //Create a new AuthAgent object
  43. newAuthAgent := AuthAgent{
  44. SessionName: sessionName,
  45. SessionStore: store,
  46. Database: sysdb,
  47. LoginRedirectionHandler: loginRedirectionHandler,
  48. Logger: systemLogger,
  49. }
  50. //Return the authAgent
  51. return &newAuthAgent
  52. }
  53. func GetSessionKey(sysdb *db.Database, logger *logger.Logger) (string, error) {
  54. sysdb.NewTable("auth")
  55. sessionKey := ""
  56. if !sysdb.KeyExists("auth", "sessionkey") {
  57. key := make([]byte, 32)
  58. rand.Read(key)
  59. sessionKey = string(key)
  60. sysdb.Write("auth", "sessionkey", sessionKey)
  61. logger.PrintAndLog("auth", "New authentication session key generated", nil)
  62. } else {
  63. logger.PrintAndLog("auth", "Authentication session key loaded from database", nil)
  64. err := sysdb.Read("auth", "sessionkey", &sessionKey)
  65. if err != nil {
  66. return "", errors.New("database read error. Is the database file corrupted?")
  67. }
  68. }
  69. return sessionKey, nil
  70. }
  71. // This function will handle an http request and redirect to the given login address if not logged in
  72. func (a *AuthAgent) HandleCheckAuth(w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  73. if a.CheckAuth(r) {
  74. //User already logged in
  75. handler(w, r)
  76. } else {
  77. //User not logged in
  78. a.LoginRedirectionHandler(w, r)
  79. }
  80. }
  81. // Handle login request, require POST username and password
  82. func (a *AuthAgent) HandleLogin(w http.ResponseWriter, r *http.Request) {
  83. //Get username from request using POST mode
  84. username, err := utils.PostPara(r, "username")
  85. if err != nil {
  86. //Username not defined
  87. a.Logger.PrintAndLog("auth", r.RemoteAddr+" trying to login with username: "+username, nil)
  88. utils.SendErrorResponse(w, "Username not defined or empty.")
  89. return
  90. }
  91. //Get password from request using POST mode
  92. password, err := utils.PostPara(r, "password")
  93. if err != nil {
  94. //Password not defined
  95. utils.SendErrorResponse(w, "Password not defined or empty.")
  96. return
  97. }
  98. //Get rememberme settings
  99. rememberme := false
  100. rmbme, _ := utils.PostPara(r, "rmbme")
  101. if rmbme == "true" {
  102. rememberme = true
  103. }
  104. //Check the database and see if this user is in the database
  105. passwordCorrect, rejectionReason := a.ValidateUsernameAndPasswordWithReason(username, password)
  106. //The database contain this user information. Check its password if it is correct
  107. if passwordCorrect {
  108. //Password correct
  109. // Set user as authenticated
  110. a.LoginUserByRequest(w, r, username, rememberme)
  111. //Print the login message to console
  112. a.Logger.PrintAndLog("auth", username+" logged in.", nil)
  113. utils.SendOK(w)
  114. } else {
  115. //Password incorrect
  116. a.Logger.PrintAndLog("auth", username+" login request rejected: "+rejectionReason, nil)
  117. utils.SendErrorResponse(w, rejectionReason)
  118. return
  119. }
  120. }
  121. func (a *AuthAgent) ValidateUsernameAndPassword(username string, password string) bool {
  122. succ, _ := a.ValidateUsernameAndPasswordWithReason(username, password)
  123. return succ
  124. }
  125. // validate the username and password, return reasons if the auth failed
  126. func (a *AuthAgent) ValidateUsernameAndPasswordWithReason(username string, password string) (bool, string) {
  127. hashedPassword := Hash(password)
  128. var passwordInDB string
  129. err := a.Database.Read("auth", "passhash/"+username, &passwordInDB)
  130. if err != nil {
  131. //User not found or db exception
  132. a.Logger.PrintAndLog("auth", username+" login with incorrect password", nil)
  133. return false, "Invalid username or password"
  134. }
  135. if passwordInDB == hashedPassword {
  136. return true, ""
  137. } else {
  138. return false, "Invalid username or password"
  139. }
  140. }
  141. // Login the user by creating a valid session for this user
  142. func (a *AuthAgent) LoginUserByRequest(w http.ResponseWriter, r *http.Request, username string, rememberme bool) {
  143. session, _ := a.SessionStore.Get(r, a.SessionName)
  144. session.Values["authenticated"] = true
  145. session.Values["username"] = username
  146. session.Values["rememberMe"] = rememberme
  147. //Check if remember me is clicked. If yes, set the maxage to 1 week.
  148. if rememberme {
  149. session.Options = &sessions.Options{
  150. MaxAge: 3600 * 24 * 7, //One week
  151. Path: "/",
  152. }
  153. } else {
  154. session.Options = &sessions.Options{
  155. MaxAge: 3600 * 1, //One hour
  156. Path: "/",
  157. }
  158. }
  159. session.Save(r, w)
  160. }
  161. // Handle logout, reply OK after logged out. WILL NOT DO REDIRECTION
  162. func (a *AuthAgent) HandleLogout(w http.ResponseWriter, r *http.Request) {
  163. username, err := a.GetUserName(w, r)
  164. if err != nil {
  165. utils.SendErrorResponse(w, "user not logged in")
  166. return
  167. }
  168. if username != "" {
  169. a.Logger.PrintAndLog("auth", username+" logged out", nil)
  170. }
  171. // Revoke users authentication
  172. err = a.Logout(w, r)
  173. if err != nil {
  174. utils.SendErrorResponse(w, "Logout failed")
  175. return
  176. }
  177. utils.SendOK(w)
  178. }
  179. func (a *AuthAgent) Logout(w http.ResponseWriter, r *http.Request) error {
  180. session, err := a.SessionStore.Get(r, a.SessionName)
  181. if err != nil {
  182. return err
  183. }
  184. session.Values["authenticated"] = false
  185. session.Values["username"] = nil
  186. session.Options.MaxAge = -1
  187. return session.Save(r, w)
  188. }
  189. // Get the current session username from request
  190. func (a *AuthAgent) GetUserName(w http.ResponseWriter, r *http.Request) (string, error) {
  191. if a.CheckAuth(r) {
  192. //This user has logged in.
  193. session, _ := a.SessionStore.Get(r, a.SessionName)
  194. return session.Values["username"].(string), nil
  195. } else {
  196. //This user has not logged in.
  197. return "", errors.New("user not logged in")
  198. }
  199. }
  200. // Get the current session user email from request
  201. func (a *AuthAgent) GetUserEmail(w http.ResponseWriter, r *http.Request) (string, error) {
  202. if a.CheckAuth(r) {
  203. //This user has logged in.
  204. session, _ := a.SessionStore.Get(r, a.SessionName)
  205. username := session.Values["username"].(string)
  206. userEmail := ""
  207. err := a.Database.Read("auth", "email/"+username, &userEmail)
  208. if err != nil {
  209. return "", err
  210. }
  211. return userEmail, nil
  212. } else {
  213. //This user has not logged in.
  214. return "", errors.New("user not logged in")
  215. }
  216. }
  217. // Check if the user has logged in, return true / false in JSON
  218. func (a *AuthAgent) CheckLogin(w http.ResponseWriter, r *http.Request) {
  219. if a.CheckAuth(r) {
  220. utils.SendJSONResponse(w, "true")
  221. } else {
  222. utils.SendJSONResponse(w, "false")
  223. }
  224. }
  225. // Handle new user register. Require POST username, password, group.
  226. func (a *AuthAgent) HandleRegister(w http.ResponseWriter, r *http.Request, callback func(string, string)) {
  227. //Get username from request
  228. newusername, err := utils.PostPara(r, "username")
  229. if err != nil {
  230. utils.SendErrorResponse(w, "Missing 'username' paramter")
  231. return
  232. }
  233. //Get password from request
  234. password, err := utils.PostPara(r, "password")
  235. if err != nil {
  236. utils.SendErrorResponse(w, "Missing 'password' paramter")
  237. return
  238. }
  239. //Get email from request
  240. email, err := utils.PostPara(r, "email")
  241. if err != nil {
  242. utils.SendErrorResponse(w, "Missing 'email' paramter")
  243. return
  244. }
  245. _, err = mail.ParseAddress(email)
  246. if err != nil {
  247. utils.SendErrorResponse(w, "Invalid or malformed email")
  248. return
  249. }
  250. //Ok to proceed create this user
  251. err = a.CreateUserAccount(newusername, password, email)
  252. if err != nil {
  253. utils.SendErrorResponse(w, err.Error())
  254. return
  255. }
  256. //Do callback if exists
  257. if callback != nil {
  258. callback(newusername, email)
  259. }
  260. //Return to the client with OK
  261. utils.SendOK(w)
  262. a.Logger.PrintAndLog("auth", "New user "+newusername+" added to system.", nil)
  263. }
  264. // Handle new user register without confirmation email. Require POST username, password, group.
  265. func (a *AuthAgent) HandleRegisterWithoutEmail(w http.ResponseWriter, r *http.Request, callback func(string, string)) {
  266. //Get username from request
  267. newusername, err := utils.PostPara(r, "username")
  268. if err != nil {
  269. utils.SendErrorResponse(w, "Missing 'username' paramter")
  270. return
  271. }
  272. //Get password from request
  273. password, err := utils.PostPara(r, "password")
  274. if err != nil {
  275. utils.SendErrorResponse(w, "Missing 'password' paramter")
  276. return
  277. }
  278. //Ok to proceed create this user
  279. err = a.CreateUserAccount(newusername, password, "")
  280. if err != nil {
  281. utils.SendErrorResponse(w, err.Error())
  282. return
  283. }
  284. //Do callback if exists
  285. if callback != nil {
  286. callback(newusername, "")
  287. }
  288. //Return to the client with OK
  289. utils.SendOK(w)
  290. a.Logger.PrintAndLog("auth", "Admin account created: "+newusername, nil)
  291. }
  292. // Check authentication from request header's session value
  293. func (a *AuthAgent) CheckAuth(r *http.Request) bool {
  294. session, err := a.SessionStore.Get(r, a.SessionName)
  295. if err != nil {
  296. return false
  297. }
  298. fmt.Println(r.RequestURI, session.Values)
  299. // Check if user is authenticated
  300. if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
  301. return false
  302. }
  303. return true
  304. }
  305. // Handle de-register of users. Require POST username.
  306. // THIS FUNCTION WILL NOT CHECK FOR PERMISSION. PLEASE USE WITH PERMISSION HANDLER
  307. func (a *AuthAgent) HandleUnregister(w http.ResponseWriter, r *http.Request) {
  308. //Check if the user is logged in
  309. if !a.CheckAuth(r) {
  310. //This user has not logged in
  311. utils.SendErrorResponse(w, "Login required to remove user from the system.")
  312. return
  313. }
  314. //Get username from request
  315. username, err := utils.PostPara(r, "username")
  316. if err != nil {
  317. utils.SendErrorResponse(w, "Missing 'username' paramter")
  318. return
  319. }
  320. err = a.UnregisterUser(username)
  321. if err != nil {
  322. utils.SendErrorResponse(w, err.Error())
  323. return
  324. }
  325. //Return to the client with OK
  326. utils.SendOK(w)
  327. a.Logger.PrintAndLog("auth", "User "+username+" has been removed from the system", nil)
  328. }
  329. func (a *AuthAgent) UnregisterUser(username string) error {
  330. //Check if the user exists in the system database.
  331. if !a.Database.KeyExists("auth", "passhash/"+username) {
  332. //This user do not exists.
  333. return errors.New("this user does not exists")
  334. }
  335. //OK! Remove the user from the database
  336. a.Database.Delete("auth", "passhash/"+username)
  337. a.Database.Delete("auth", "email/"+username)
  338. return nil
  339. }
  340. // Get the number of users in the system
  341. func (a *AuthAgent) GetUserCounts() int {
  342. entries, _ := a.Database.ListTable("auth")
  343. usercount := 0
  344. for _, keypairs := range entries {
  345. if strings.Contains(string(keypairs[0]), "passhash/") {
  346. //This is a user registry
  347. usercount++
  348. }
  349. }
  350. if usercount == 0 {
  351. a.Logger.PrintAndLog("auth", "There are no user in the database", nil)
  352. }
  353. return usercount
  354. }
  355. // List all username within the system
  356. func (a *AuthAgent) ListUsers() []string {
  357. entries, _ := a.Database.ListTable("auth")
  358. results := []string{}
  359. for _, keypairs := range entries {
  360. if strings.Contains(string(keypairs[0]), "passhash/") {
  361. username := strings.Split(string(keypairs[0]), "/")[1]
  362. results = append(results, username)
  363. }
  364. }
  365. return results
  366. }
  367. // Check if the given username exists
  368. func (a *AuthAgent) UserExists(username string) bool {
  369. userpasswordhash := ""
  370. err := a.Database.Read("auth", "passhash/"+username, &userpasswordhash)
  371. if err != nil || userpasswordhash == "" {
  372. return false
  373. }
  374. return true
  375. }
  376. // Update the session expire time given the request header.
  377. func (a *AuthAgent) UpdateSessionExpireTime(w http.ResponseWriter, r *http.Request) bool {
  378. session, _ := a.SessionStore.Get(r, a.SessionName)
  379. if session.Values["authenticated"].(bool) {
  380. //User authenticated. Extend its expire time
  381. rememberme := session.Values["rememberMe"].(bool)
  382. //Extend the session expire time
  383. if rememberme {
  384. session.Options = &sessions.Options{
  385. MaxAge: 3600 * 24 * 7, //One week
  386. Path: "/",
  387. }
  388. } else {
  389. session.Options = &sessions.Options{
  390. MaxAge: 3600 * 1, //One hour
  391. Path: "/",
  392. }
  393. }
  394. session.Save(r, w)
  395. return true
  396. } else {
  397. return false
  398. }
  399. }
  400. // Create user account
  401. func (a *AuthAgent) CreateUserAccount(newusername string, password string, email string) error {
  402. //Check user already exists
  403. if a.UserExists(newusername) {
  404. return errors.New("user with same name already exists")
  405. }
  406. key := newusername
  407. hashedPassword := Hash(password)
  408. err := a.Database.Write("auth", "passhash/"+key, hashedPassword)
  409. if err != nil {
  410. return err
  411. }
  412. if email != "" {
  413. err = a.Database.Write("auth", "email/"+key, email)
  414. if err != nil {
  415. return err
  416. }
  417. }
  418. return nil
  419. }
  420. // Hash the given raw string into sha512 hash
  421. func Hash(raw string) string {
  422. h := sha512.New()
  423. h.Write([]byte(raw))
  424. return hex.EncodeToString(h.Sum(nil))
  425. }