user.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package user
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "net/url"
  9. "strings"
  10. "code.google.com/p/goauth2/oauth"
  11. "github.com/go-martini/martini"
  12. "github.com/martini-contrib/oauth2"
  13. "github.com/gogits/gogs/models"
  14. "github.com/gogits/gogs/modules/auth"
  15. "github.com/gogits/gogs/modules/base"
  16. "github.com/gogits/gogs/modules/log"
  17. "github.com/gogits/gogs/modules/mailer"
  18. "github.com/gogits/gogs/modules/middleware"
  19. )
  20. func Dashboard(ctx *middleware.Context) {
  21. ctx.Data["Title"] = "Dashboard"
  22. ctx.Data["PageIsUserDashboard"] = true
  23. repos, err := models.GetRepositories(&models.User{Id: ctx.User.Id})
  24. if err != nil {
  25. ctx.Handle(200, "user.Dashboard", err)
  26. return
  27. }
  28. ctx.Data["MyRepos"] = repos
  29. feeds, err := models.GetFeeds(ctx.User.Id, 0, false)
  30. if err != nil {
  31. ctx.Handle(200, "user.Dashboard", err)
  32. return
  33. }
  34. ctx.Data["Feeds"] = feeds
  35. ctx.HTML(200, "user/dashboard")
  36. }
  37. func Profile(ctx *middleware.Context, params martini.Params) {
  38. ctx.Data["Title"] = "Profile"
  39. // TODO: Need to check view self or others.
  40. user, err := models.GetUserByName(params["username"])
  41. if err != nil {
  42. ctx.Handle(200, "user.Profile", err)
  43. return
  44. }
  45. ctx.Data["Owner"] = user
  46. tab := ctx.Query("tab")
  47. ctx.Data["TabName"] = tab
  48. switch tab {
  49. case "activity":
  50. feeds, err := models.GetFeeds(user.Id, 0, true)
  51. if err != nil {
  52. ctx.Handle(200, "user.Profile", err)
  53. return
  54. }
  55. ctx.Data["Feeds"] = feeds
  56. default:
  57. repos, err := models.GetRepositories(user)
  58. if err != nil {
  59. ctx.Handle(200, "user.Profile", err)
  60. return
  61. }
  62. ctx.Data["Repos"] = repos
  63. }
  64. ctx.Data["PageIsUserProfile"] = true
  65. ctx.HTML(200, "user/profile")
  66. }
  67. // github && google && ...
  68. func SocialSignIn(tokens oauth2.Tokens) {
  69. transport := &oauth.Transport{}
  70. transport.Token = &oauth.Token{
  71. AccessToken: tokens.Access(),
  72. RefreshToken: tokens.Refresh(),
  73. Expiry: tokens.ExpiryTime(),
  74. Extra: tokens.ExtraData(),
  75. }
  76. // Github API refer: https://developer.github.com/v3/users/
  77. // FIXME: need to judge url
  78. type GithubUser struct {
  79. Id int `json:"id"`
  80. Name string `json:"login"`
  81. Email string `json:"email"`
  82. }
  83. // Make the request.
  84. scope := "https://api.github.com/user"
  85. r, err := transport.Client().Get(scope)
  86. if err != nil {
  87. log.Error("connect with github error: %s", err)
  88. // FIXME: handle error page
  89. return
  90. }
  91. defer r.Body.Close()
  92. user := &GithubUser{}
  93. err = json.NewDecoder(r.Body).Decode(user)
  94. if err != nil {
  95. log.Error("Get: %s", err)
  96. }
  97. log.Info("login: %s", user.Name)
  98. // FIXME: login here, user email to check auth, if not registe, then generate a uniq username
  99. }
  100. func SignIn(ctx *middleware.Context, form auth.LogInForm) {
  101. ctx.Data["Title"] = "Log In"
  102. if ctx.Req.Method == "GET" {
  103. // Check auto-login.
  104. userName := ctx.GetCookie(base.CookieUserName)
  105. if len(userName) == 0 {
  106. ctx.HTML(200, "user/signin")
  107. return
  108. }
  109. isSucceed := false
  110. defer func() {
  111. if !isSucceed {
  112. log.Trace("%s auto-login cookie cleared: %s", ctx.Req.RequestURI, userName)
  113. ctx.SetCookie(base.CookieUserName, "", -1)
  114. ctx.SetCookie(base.CookieRememberName, "", -1)
  115. }
  116. }()
  117. user, err := models.GetUserByName(userName)
  118. if err != nil {
  119. ctx.HTML(200, "user/signin")
  120. return
  121. }
  122. secret := base.EncodeMd5(user.Rands + user.Passwd)
  123. value, _ := ctx.GetSecureCookie(secret, base.CookieRememberName)
  124. if value != user.Name {
  125. ctx.HTML(200, "user/signin")
  126. return
  127. }
  128. isSucceed = true
  129. ctx.Session.Set("userId", user.Id)
  130. ctx.Session.Set("userName", user.Name)
  131. redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to"))
  132. if len(redirectTo) > 0 {
  133. ctx.SetCookie("redirect_to", "", -1)
  134. ctx.Redirect(redirectTo)
  135. } else {
  136. ctx.Redirect("/")
  137. }
  138. return
  139. }
  140. if ctx.HasError() {
  141. ctx.HTML(200, "user/signin")
  142. return
  143. }
  144. user, err := models.LoginUserPlain(form.UserName, form.Password)
  145. if err != nil {
  146. if err == models.ErrUserNotExist {
  147. log.Trace("%s Log in failed: %s/%s", ctx.Req.RequestURI, form.UserName, form.Password)
  148. ctx.RenderWithErr("Username or password is not correct", "user/signin", &form)
  149. return
  150. }
  151. ctx.Handle(200, "user.SignIn", err)
  152. return
  153. }
  154. if form.Remember == "on" {
  155. secret := base.EncodeMd5(user.Rands + user.Passwd)
  156. days := 86400 * base.LogInRememberDays
  157. ctx.SetCookie(base.CookieUserName, user.Name, days)
  158. ctx.SetSecureCookie(secret, base.CookieRememberName, user.Name, days)
  159. }
  160. ctx.Session.Set("userId", user.Id)
  161. ctx.Session.Set("userName", user.Name)
  162. redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to"))
  163. if len(redirectTo) > 0 {
  164. ctx.SetCookie("redirect_to", "", -1)
  165. ctx.Redirect(redirectTo)
  166. } else {
  167. ctx.Redirect("/")
  168. }
  169. }
  170. func SignOut(ctx *middleware.Context) {
  171. ctx.Session.Delete("userId")
  172. ctx.Session.Delete("userName")
  173. ctx.SetCookie(base.CookieUserName, "", -1)
  174. ctx.SetCookie(base.CookieRememberName, "", -1)
  175. ctx.Redirect("/")
  176. }
  177. func SignUp(ctx *middleware.Context, form auth.RegisterForm) {
  178. ctx.Data["Title"] = "Sign Up"
  179. ctx.Data["PageIsSignUp"] = true
  180. if base.Service.DisenableRegisteration {
  181. ctx.Data["DisenableRegisteration"] = true
  182. ctx.HTML(200, "user/signup")
  183. return
  184. }
  185. if ctx.Req.Method == "GET" {
  186. ctx.HTML(200, "user/signup")
  187. return
  188. }
  189. if form.Password != form.RetypePasswd {
  190. ctx.Data["HasError"] = true
  191. ctx.Data["Err_Password"] = true
  192. ctx.Data["Err_RetypePasswd"] = true
  193. ctx.Data["ErrorMsg"] = "Password and re-type password are not same"
  194. auth.AssignForm(form, ctx.Data)
  195. }
  196. if ctx.HasError() {
  197. ctx.HTML(200, "user/signup")
  198. return
  199. }
  200. u := &models.User{
  201. Name: form.UserName,
  202. Email: form.Email,
  203. Passwd: form.Password,
  204. IsActive: !base.Service.RegisterEmailConfirm,
  205. }
  206. var err error
  207. if u, err = models.RegisterUser(u); err != nil {
  208. switch err {
  209. case models.ErrUserAlreadyExist:
  210. ctx.RenderWithErr("Username has been already taken", "user/signup", &form)
  211. case models.ErrEmailAlreadyUsed:
  212. ctx.RenderWithErr("E-mail address has been already used", "user/signup", &form)
  213. case models.ErrUserNameIllegal:
  214. ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), "user/signup", &form)
  215. default:
  216. ctx.Handle(200, "user.SignUp", err)
  217. }
  218. return
  219. }
  220. log.Trace("%s User created: %s", ctx.Req.RequestURI, strings.ToLower(form.UserName))
  221. // Send confirmation e-mail.
  222. if base.Service.RegisterEmailConfirm && u.Id > 1 {
  223. mailer.SendRegisterMail(ctx.Render, u)
  224. ctx.Data["IsSendRegisterMail"] = true
  225. ctx.Data["Email"] = u.Email
  226. ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60
  227. ctx.HTML(200, "user/active")
  228. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  229. log.Error("Set cache(MailResendLimit) fail: %v", err)
  230. }
  231. return
  232. }
  233. ctx.Redirect("/user/login")
  234. }
  235. func Delete(ctx *middleware.Context) {
  236. ctx.Data["Title"] = "Delete Account"
  237. ctx.Data["PageIsUserSetting"] = true
  238. ctx.Data["IsUserPageSettingDelete"] = true
  239. if ctx.Req.Method == "GET" {
  240. ctx.HTML(200, "user/delete")
  241. return
  242. }
  243. tmpUser := models.User{Passwd: ctx.Query("password")}
  244. tmpUser.EncodePasswd()
  245. if len(tmpUser.Passwd) == 0 || tmpUser.Passwd != ctx.User.Passwd {
  246. ctx.Data["HasError"] = true
  247. ctx.Data["ErrorMsg"] = "Password is not correct. Make sure you are owner of this account."
  248. } else {
  249. if err := models.DeleteUser(ctx.User); err != nil {
  250. ctx.Data["HasError"] = true
  251. switch err {
  252. case models.ErrUserOwnRepos:
  253. ctx.Data["ErrorMsg"] = "Your account still have ownership of repository, you have to delete or transfer them first."
  254. default:
  255. ctx.Handle(200, "user.Delete", err)
  256. return
  257. }
  258. } else {
  259. ctx.Redirect("/")
  260. return
  261. }
  262. }
  263. ctx.HTML(200, "user/delete")
  264. }
  265. const (
  266. TPL_FEED = `<i class="icon fa fa-%s"></i>
  267. <div class="info"><span class="meta">%s</span><br>%s</div>`
  268. )
  269. func Feeds(ctx *middleware.Context, form auth.FeedsForm) {
  270. actions, err := models.GetFeeds(form.UserId, form.Page*20, false)
  271. if err != nil {
  272. ctx.JSON(500, err)
  273. }
  274. feeds := make([]string, len(actions))
  275. for i := range actions {
  276. feeds[i] = fmt.Sprintf(TPL_FEED, base.ActionIcon(actions[i].OpType),
  277. base.TimeSince(actions[i].Created), base.ActionDesc(actions[i]))
  278. }
  279. ctx.JSON(200, &feeds)
  280. }
  281. func Issues(ctx *middleware.Context) {
  282. ctx.Data["Title"] = "Your Issues"
  283. ctx.Data["ViewType"] = "all"
  284. page, _ := base.StrTo(ctx.Query("page")).Int()
  285. repoId, _ := base.StrTo(ctx.Query("repoid")).Int64()
  286. ctx.Data["RepoId"] = repoId
  287. var posterId int64 = 0
  288. if ctx.Query("type") == "created_by" {
  289. posterId = ctx.User.Id
  290. ctx.Data["ViewType"] = "created_by"
  291. }
  292. // Get all repositories.
  293. repos, err := models.GetRepositories(ctx.User)
  294. if err != nil {
  295. ctx.Handle(200, "user.Issues(get repositories)", err)
  296. return
  297. }
  298. showRepos := make([]models.Repository, 0, len(repos))
  299. isShowClosed := ctx.Query("state") == "closed"
  300. var closedIssueCount, createdByCount, allIssueCount int
  301. // Get all issues.
  302. allIssues := make([]models.Issue, 0, 5*len(repos))
  303. for i, repo := range repos {
  304. issues, err := models.GetIssues(0, repo.Id, posterId, 0, page, isShowClosed, false, "", "")
  305. if err != nil {
  306. ctx.Handle(200, "user.Issues(get issues)", err)
  307. return
  308. }
  309. allIssueCount += repo.NumIssues
  310. closedIssueCount += repo.NumClosedIssues
  311. // Set repository information to issues.
  312. for j := range issues {
  313. issues[j].Repo = &repos[i]
  314. }
  315. allIssues = append(allIssues, issues...)
  316. repos[i].NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  317. if repos[i].NumOpenIssues > 0 {
  318. showRepos = append(showRepos, repos[i])
  319. }
  320. }
  321. showIssues := make([]models.Issue, 0, len(allIssues))
  322. ctx.Data["IsShowClosed"] = isShowClosed
  323. // Get posters and filter issues.
  324. for i := range allIssues {
  325. u, err := models.GetUserById(allIssues[i].PosterId)
  326. if err != nil {
  327. ctx.Handle(200, "user.Issues(get poster): %v", err)
  328. return
  329. }
  330. allIssues[i].Poster = u
  331. if u.Id == ctx.User.Id {
  332. createdByCount++
  333. }
  334. if repoId > 0 && repoId != allIssues[i].Repo.Id {
  335. continue
  336. }
  337. if isShowClosed == allIssues[i].IsClosed {
  338. showIssues = append(showIssues, allIssues[i])
  339. }
  340. }
  341. ctx.Data["Repos"] = showRepos
  342. ctx.Data["Issues"] = showIssues
  343. ctx.Data["AllIssueCount"] = allIssueCount
  344. ctx.Data["ClosedIssueCount"] = closedIssueCount
  345. ctx.Data["OpenIssueCount"] = allIssueCount - closedIssueCount
  346. ctx.Data["CreatedByCount"] = createdByCount
  347. ctx.HTML(200, "issue/user")
  348. }
  349. func Pulls(ctx *middleware.Context) {
  350. ctx.HTML(200, "user/pulls")
  351. }
  352. func Stars(ctx *middleware.Context) {
  353. ctx.HTML(200, "user/stars")
  354. }
  355. func Activate(ctx *middleware.Context) {
  356. code := ctx.Query("code")
  357. if len(code) == 0 {
  358. ctx.Data["IsActivatePage"] = true
  359. if ctx.User.IsActive {
  360. ctx.Handle(404, "user.Activate", nil)
  361. return
  362. }
  363. // Resend confirmation e-mail.
  364. if base.Service.RegisterEmailConfirm {
  365. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  366. ctx.Data["ResendLimited"] = true
  367. } else {
  368. ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60
  369. mailer.SendActiveMail(ctx.Render, ctx.User)
  370. }
  371. } else {
  372. ctx.Data["ServiceNotEnabled"] = true
  373. }
  374. ctx.HTML(200, "user/active")
  375. return
  376. }
  377. // Verify code.
  378. if user := models.VerifyUserActiveCode(code); user != nil {
  379. user.IsActive = true
  380. user.Rands = models.GetUserSalt()
  381. models.UpdateUser(user)
  382. log.Trace("%s User activated: %s", ctx.Req.RequestURI, user.LowerName)
  383. ctx.Session.Set("userId", user.Id)
  384. ctx.Session.Set("userName", user.Name)
  385. ctx.Redirect("/")
  386. return
  387. }
  388. ctx.Data["IsActivateFailed"] = true
  389. ctx.HTML(200, "user/active")
  390. }