You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1651 lines
44 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
7 years ago
7 years ago
10 years ago
10 years ago
10 years ago
7 years ago
10 years ago
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
9 years ago
7 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
10 years ago
7 years ago
7 years ago
8 years ago
9 years ago
8 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
  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 models
  5. import (
  6. "bytes"
  7. "container/list"
  8. "crypto/md5"
  9. "crypto/sha256"
  10. "crypto/subtle"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. "image"
  15. // Needed for jpeg support
  16. _ "image/jpeg"
  17. "image/png"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "time"
  22. "unicode/utf8"
  23. "github.com/Unknwon/com"
  24. "github.com/go-xorm/builder"
  25. "github.com/go-xorm/xorm"
  26. "github.com/nfnt/resize"
  27. "golang.org/x/crypto/pbkdf2"
  28. "golang.org/x/crypto/ssh"
  29. "code.gitea.io/git"
  30. api "code.gitea.io/sdk/gitea"
  31. "code.gitea.io/gitea/modules/avatar"
  32. "code.gitea.io/gitea/modules/base"
  33. "code.gitea.io/gitea/modules/generate"
  34. "code.gitea.io/gitea/modules/log"
  35. "code.gitea.io/gitea/modules/setting"
  36. "code.gitea.io/gitea/modules/util"
  37. )
  38. // UserType defines the user type
  39. type UserType int
  40. const (
  41. // UserTypeIndividual defines an individual user
  42. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  43. // UserTypeOrganization defines an organization
  44. UserTypeOrganization
  45. )
  46. const syncExternalUsers = "sync_external_users"
  47. var (
  48. // ErrUserNotKeyOwner user does not own this key error
  49. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  50. // ErrEmailNotExist e-mail does not exist error
  51. ErrEmailNotExist = errors.New("E-mail does not exist")
  52. // ErrEmailNotActivated e-mail address has not been activated error
  53. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  54. // ErrUserNameIllegal user name contains illegal characters error
  55. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  56. // ErrLoginSourceNotActived login source is not actived error
  57. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  58. // ErrUnsupportedLoginType login source is unknown error
  59. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  60. )
  61. // User represents the object of individual and member of organization.
  62. type User struct {
  63. ID int64 `xorm:"pk autoincr"`
  64. LowerName string `xorm:"UNIQUE NOT NULL"`
  65. Name string `xorm:"UNIQUE NOT NULL"`
  66. FullName string
  67. // Email is the primary email address (to be used for communication)
  68. Email string `xorm:"NOT NULL"`
  69. KeepEmailPrivate bool
  70. Passwd string `xorm:"NOT NULL"`
  71. // MustChangePassword is an attribute that determines if a user
  72. // is to change his/her password after registration.
  73. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  74. LoginType LoginType
  75. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  76. LoginName string
  77. Type UserType
  78. OwnedOrgs []*User `xorm:"-"`
  79. Orgs []*User `xorm:"-"`
  80. Repos []*Repository `xorm:"-"`
  81. Location string
  82. Website string
  83. Rands string `xorm:"VARCHAR(10)"`
  84. Salt string `xorm:"VARCHAR(10)"`
  85. Language string `xorm:"VARCHAR(5)"`
  86. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  87. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  88. LastLoginUnix util.TimeStamp `xorm:"INDEX"`
  89. // Remember visibility choice for convenience, true for private
  90. LastRepoVisibility bool
  91. // Maximum repository creation limit, -1 means use global default
  92. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  93. // Permissions
  94. IsActive bool `xorm:"INDEX"` // Activate primary email
  95. IsAdmin bool
  96. AllowGitHook bool
  97. AllowImportLocal bool // Allow migrate repository by local path
  98. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  99. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  100. // Avatar
  101. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  102. AvatarEmail string `xorm:"NOT NULL"`
  103. UseCustomAvatar bool
  104. // Counters
  105. NumFollowers int
  106. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  107. NumStars int
  108. NumRepos int
  109. // For organization
  110. Description string
  111. NumTeams int
  112. NumMembers int
  113. Teams []*Team `xorm:"-"`
  114. Members []*User `xorm:"-"`
  115. // Preferences
  116. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  117. }
  118. // BeforeUpdate is invoked from XORM before updating this object.
  119. func (u *User) BeforeUpdate() {
  120. if u.MaxRepoCreation < -1 {
  121. u.MaxRepoCreation = -1
  122. }
  123. // Organization does not need email
  124. u.Email = strings.ToLower(u.Email)
  125. if !u.IsOrganization() {
  126. if len(u.AvatarEmail) == 0 {
  127. u.AvatarEmail = u.Email
  128. }
  129. if len(u.AvatarEmail) > 0 && u.Avatar == "" {
  130. u.Avatar = base.HashEmail(u.AvatarEmail)
  131. }
  132. }
  133. u.LowerName = strings.ToLower(u.Name)
  134. u.Location = base.TruncateString(u.Location, 255)
  135. u.Website = base.TruncateString(u.Website, 255)
  136. u.Description = base.TruncateString(u.Description, 255)
  137. }
  138. // SetLastLogin set time to last login
  139. func (u *User) SetLastLogin() {
  140. u.LastLoginUnix = util.TimeStampNow()
  141. }
  142. // UpdateDiffViewStyle updates the users diff view style
  143. func (u *User) UpdateDiffViewStyle(style string) error {
  144. u.DiffViewStyle = style
  145. return UpdateUserCols(u, "diff_view_style")
  146. }
  147. // getEmail returns an noreply email, if the user has set to keep his
  148. // email address private, otherwise the primary email address.
  149. func (u *User) getEmail() string {
  150. if u.KeepEmailPrivate {
  151. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  152. }
  153. return u.Email
  154. }
  155. // APIFormat converts a User to api.User
  156. func (u *User) APIFormat() *api.User {
  157. return &api.User{
  158. ID: u.ID,
  159. UserName: u.Name,
  160. FullName: u.FullName,
  161. Email: u.getEmail(),
  162. AvatarURL: u.AvatarLink(),
  163. Language: u.Language,
  164. }
  165. }
  166. // IsLocal returns true if user login type is LoginPlain.
  167. func (u *User) IsLocal() bool {
  168. return u.LoginType <= LoginPlain
  169. }
  170. // IsOAuth2 returns true if user login type is LoginOAuth2.
  171. func (u *User) IsOAuth2() bool {
  172. return u.LoginType == LoginOAuth2
  173. }
  174. // HasForkedRepo checks if user has already forked a repository with given ID.
  175. func (u *User) HasForkedRepo(repoID int64) bool {
  176. _, has := HasForkedRepo(u.ID, repoID)
  177. return has
  178. }
  179. // MaxCreationLimit returns the number of repositories a user is allowed to create
  180. func (u *User) MaxCreationLimit() int {
  181. if u.MaxRepoCreation <= -1 {
  182. return setting.Repository.MaxCreationLimit
  183. }
  184. return u.MaxRepoCreation
  185. }
  186. // CanCreateRepo returns if user login can create a repository
  187. func (u *User) CanCreateRepo() bool {
  188. if u.IsAdmin {
  189. return true
  190. }
  191. if u.MaxRepoCreation <= -1 {
  192. if setting.Repository.MaxCreationLimit <= -1 {
  193. return true
  194. }
  195. return u.NumRepos < setting.Repository.MaxCreationLimit
  196. }
  197. return u.NumRepos < u.MaxRepoCreation
  198. }
  199. // CanCreateOrganization returns true if user can create organisation.
  200. func (u *User) CanCreateOrganization() bool {
  201. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  202. }
  203. // CanEditGitHook returns true if user can edit Git hooks.
  204. func (u *User) CanEditGitHook() bool {
  205. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  206. }
  207. // CanImportLocal returns true if user can migrate repository by local path.
  208. func (u *User) CanImportLocal() bool {
  209. if !setting.ImportLocalPaths {
  210. return false
  211. }
  212. return u.IsAdmin || u.AllowImportLocal
  213. }
  214. // DashboardLink returns the user dashboard page link.
  215. func (u *User) DashboardLink() string {
  216. if u.IsOrganization() {
  217. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  218. }
  219. return setting.AppSubURL + "/"
  220. }
  221. // HomeLink returns the user or organization home page link.
  222. func (u *User) HomeLink() string {
  223. return setting.AppSubURL + "/" + u.Name
  224. }
  225. // HTMLURL returns the user or organization's full link.
  226. func (u *User) HTMLURL() string {
  227. return setting.AppURL + u.Name
  228. }
  229. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  230. func (u *User) GenerateEmailActivateCode(email string) string {
  231. code := base.CreateTimeLimitCode(
  232. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  233. setting.Service.ActiveCodeLives, nil)
  234. // Add tail hex username
  235. code += hex.EncodeToString([]byte(u.LowerName))
  236. return code
  237. }
  238. // GenerateActivateCode generates an activate code based on user information.
  239. func (u *User) GenerateActivateCode() string {
  240. return u.GenerateEmailActivateCode(u.Email)
  241. }
  242. // CustomAvatarPath returns user custom avatar file path.
  243. func (u *User) CustomAvatarPath() string {
  244. return filepath.Join(setting.AvatarUploadPath, u.Avatar)
  245. }
  246. // GenerateRandomAvatar generates a random avatar for user.
  247. func (u *User) GenerateRandomAvatar() error {
  248. return u.generateRandomAvatar(x)
  249. }
  250. func (u *User) generateRandomAvatar(e Engine) error {
  251. seed := u.Email
  252. if len(seed) == 0 {
  253. seed = u.Name
  254. }
  255. img, err := avatar.RandomImage([]byte(seed))
  256. if err != nil {
  257. return fmt.Errorf("RandomImage: %v", err)
  258. }
  259. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  260. // since random image is not a user's photo, there is no security for enumable
  261. if u.Avatar == "" {
  262. u.Avatar = fmt.Sprintf("%d", u.ID)
  263. }
  264. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  265. return fmt.Errorf("MkdirAll: %v", err)
  266. }
  267. fw, err := os.Create(u.CustomAvatarPath())
  268. if err != nil {
  269. return fmt.Errorf("Create: %v", err)
  270. }
  271. defer fw.Close()
  272. if _, err := e.ID(u.ID).Cols("avatar").Update(u); err != nil {
  273. return err
  274. }
  275. if err = png.Encode(fw, img); err != nil {
  276. return fmt.Errorf("Encode: %v", err)
  277. }
  278. log.Info("New random avatar created: %d", u.ID)
  279. return nil
  280. }
  281. // SizedRelAvatarLink returns a relative link to the user's avatar. When
  282. // applicable, the link is for an avatar of the indicated size (in pixels).
  283. func (u *User) SizedRelAvatarLink(size int) string {
  284. if u.ID == -1 {
  285. return base.DefaultAvatarLink()
  286. }
  287. switch {
  288. case u.UseCustomAvatar:
  289. if !com.IsFile(u.CustomAvatarPath()) {
  290. return base.DefaultAvatarLink()
  291. }
  292. return setting.AppSubURL + "/avatars/" + u.Avatar
  293. case setting.DisableGravatar, setting.OfflineMode:
  294. if !com.IsFile(u.CustomAvatarPath()) {
  295. if err := u.GenerateRandomAvatar(); err != nil {
  296. log.Error(3, "GenerateRandomAvatar: %v", err)
  297. }
  298. }
  299. return setting.AppSubURL + "/avatars/" + u.Avatar
  300. }
  301. return base.SizedAvatarLink(u.AvatarEmail, size)
  302. }
  303. // RelAvatarLink returns a relative link to the user's avatar. The link
  304. // may either be a sub-URL to this site, or a full URL to an external avatar
  305. // service.
  306. func (u *User) RelAvatarLink() string {
  307. return u.SizedRelAvatarLink(base.DefaultAvatarSize)
  308. }
  309. // AvatarLink returns user avatar absolute link.
  310. func (u *User) AvatarLink() string {
  311. link := u.RelAvatarLink()
  312. if link[0] == '/' && link[1] != '/' {
  313. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  314. }
  315. return link
  316. }
  317. // GetFollowers returns range of user's followers.
  318. func (u *User) GetFollowers(page int) ([]*User, error) {
  319. users := make([]*User, 0, ItemsPerPage)
  320. sess := x.
  321. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  322. Where("follow.follow_id=?", u.ID).
  323. Join("LEFT", "follow", "`user`.id=follow.user_id")
  324. return users, sess.Find(&users)
  325. }
  326. // IsFollowing returns true if user is following followID.
  327. func (u *User) IsFollowing(followID int64) bool {
  328. return IsFollowing(u.ID, followID)
  329. }
  330. // GetFollowing returns range of user's following.
  331. func (u *User) GetFollowing(page int) ([]*User, error) {
  332. users := make([]*User, 0, ItemsPerPage)
  333. sess := x.
  334. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  335. Where("follow.user_id=?", u.ID).
  336. Join("LEFT", "follow", "`user`.id=follow.follow_id")
  337. return users, sess.Find(&users)
  338. }
  339. // NewGitSig generates and returns the signature of given user.
  340. func (u *User) NewGitSig() *git.Signature {
  341. return &git.Signature{
  342. Name: u.DisplayName(),
  343. Email: u.getEmail(),
  344. When: time.Now(),
  345. }
  346. }
  347. func hashPassword(passwd, salt string) string {
  348. tempPasswd := pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  349. return fmt.Sprintf("%x", tempPasswd)
  350. }
  351. // HashPassword hashes a password using PBKDF.
  352. func (u *User) HashPassword(passwd string) {
  353. u.Passwd = hashPassword(passwd, u.Salt)
  354. }
  355. // ValidatePassword checks if given password matches the one belongs to the user.
  356. func (u *User) ValidatePassword(passwd string) bool {
  357. tempHash := hashPassword(passwd, u.Salt)
  358. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1
  359. }
  360. // IsPasswordSet checks if the password is set or left empty
  361. func (u *User) IsPasswordSet() bool {
  362. return !u.ValidatePassword("")
  363. }
  364. // UploadAvatar saves custom avatar for user.
  365. // FIXME: split uploads to different subdirs in case we have massive users.
  366. func (u *User) UploadAvatar(data []byte) error {
  367. imgCfg, _, err := image.DecodeConfig(bytes.NewReader(data))
  368. if err != nil {
  369. return fmt.Errorf("DecodeConfig: %v", err)
  370. }
  371. if imgCfg.Width > setting.AvatarMaxWidth {
  372. return fmt.Errorf("Image width is to large: %d > %d", imgCfg.Width, setting.AvatarMaxWidth)
  373. }
  374. if imgCfg.Height > setting.AvatarMaxHeight {
  375. return fmt.Errorf("Image height is to large: %d > %d", imgCfg.Height, setting.AvatarMaxHeight)
  376. }
  377. img, _, err := image.Decode(bytes.NewReader(data))
  378. if err != nil {
  379. return fmt.Errorf("Decode: %v", err)
  380. }
  381. m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor)
  382. sess := x.NewSession()
  383. defer sess.Close()
  384. if err = sess.Begin(); err != nil {
  385. return err
  386. }
  387. u.UseCustomAvatar = true
  388. u.Avatar = fmt.Sprintf("%x", md5.Sum(data))
  389. if err = updateUser(sess, u); err != nil {
  390. return fmt.Errorf("updateUser: %v", err)
  391. }
  392. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  393. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  394. }
  395. fw, err := os.Create(u.CustomAvatarPath())
  396. if err != nil {
  397. return fmt.Errorf("Create: %v", err)
  398. }
  399. defer fw.Close()
  400. if err = png.Encode(fw, m); err != nil {
  401. return fmt.Errorf("Encode: %v", err)
  402. }
  403. return sess.Commit()
  404. }
  405. // DeleteAvatar deletes the user's custom avatar.
  406. func (u *User) DeleteAvatar() error {
  407. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  408. if len(u.Avatar) > 0 {
  409. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  410. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  411. }
  412. }
  413. u.UseCustomAvatar = false
  414. u.Avatar = ""
  415. if _, err := x.ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
  416. return fmt.Errorf("UpdateUser: %v", err)
  417. }
  418. return nil
  419. }
  420. // IsOrganization returns true if user is actually a organization.
  421. func (u *User) IsOrganization() bool {
  422. return u.Type == UserTypeOrganization
  423. }
  424. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  425. func (u *User) IsUserOrgOwner(orgID int64) bool {
  426. isOwner, err := IsOrganizationOwner(orgID, u.ID)
  427. if err != nil {
  428. log.Error(4, "IsOrganizationOwner: %v", err)
  429. return false
  430. }
  431. return isOwner
  432. }
  433. // IsPublicMember returns true if user public his/her membership in given organization.
  434. func (u *User) IsPublicMember(orgID int64) bool {
  435. isMember, err := IsPublicMembership(orgID, u.ID)
  436. if err != nil {
  437. log.Error(4, "IsPublicMembership: %v", err)
  438. return false
  439. }
  440. return isMember
  441. }
  442. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  443. return e.
  444. Where("uid=?", u.ID).
  445. Count(new(OrgUser))
  446. }
  447. // GetOrganizationCount returns count of membership of organization of user.
  448. func (u *User) GetOrganizationCount() (int64, error) {
  449. return u.getOrganizationCount(x)
  450. }
  451. // GetRepositories returns repositories that user owns, including private repositories.
  452. func (u *User) GetRepositories(page, pageSize int) (err error) {
  453. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize, "")
  454. return err
  455. }
  456. // GetRepositoryIDs returns repositories IDs where user owned and has unittypes
  457. func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) {
  458. var ids []int64
  459. sess := x.Table("repository").Cols("repository.id")
  460. if len(units) > 0 {
  461. sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
  462. sess = sess.In("repo_unit.type", units)
  463. }
  464. return ids, sess.Where("owner_id = ?", u.ID).Find(&ids)
  465. }
  466. // GetOrgRepositoryIDs returns repositories IDs where user's team owned and has unittypes
  467. func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) {
  468. var ids []int64
  469. sess := x.Table("repository").
  470. Cols("repository.id").
  471. Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
  472. Join("INNER", "team_repo", "repository.is_private != ? OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true)
  473. if len(units) > 0 {
  474. sess = sess.Join("INNER", "team_unit", "team_unit.team_id = team_user.team_id")
  475. sess = sess.In("team_unit.type", units)
  476. }
  477. return ids, sess.
  478. Where("team_user.uid = ?", u.ID).
  479. GroupBy("repository.id").Find(&ids)
  480. }
  481. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  482. func (u *User) GetAccessRepoIDs(units ...UnitType) ([]int64, error) {
  483. ids, err := u.GetRepositoryIDs(units...)
  484. if err != nil {
  485. return nil, err
  486. }
  487. ids2, err := u.GetOrgRepositoryIDs(units...)
  488. if err != nil {
  489. return nil, err
  490. }
  491. return append(ids, ids2...), nil
  492. }
  493. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  494. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  495. return GetUserMirrorRepositories(u.ID)
  496. }
  497. // GetOwnedOrganizations returns all organizations that user owns.
  498. func (u *User) GetOwnedOrganizations() (err error) {
  499. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  500. return err
  501. }
  502. // GetOrganizations returns all organizations that user belongs to.
  503. func (u *User) GetOrganizations(all bool) error {
  504. ous, err := GetOrgUsersByUserID(u.ID, all)
  505. if err != nil {
  506. return err
  507. }
  508. u.Orgs = make([]*User, len(ous))
  509. for i, ou := range ous {
  510. u.Orgs[i], err = GetUserByID(ou.OrgID)
  511. if err != nil {
  512. return err
  513. }
  514. }
  515. return nil
  516. }
  517. // DisplayName returns full name if it's not empty,
  518. // returns username otherwise.
  519. func (u *User) DisplayName() string {
  520. if len(u.FullName) > 0 {
  521. return u.FullName
  522. }
  523. return u.Name
  524. }
  525. // ShortName ellipses username to length
  526. func (u *User) ShortName(length int) string {
  527. return base.EllipsisString(u.Name, length)
  528. }
  529. // IsMailable checks if a user is eligible
  530. // to receive emails.
  531. func (u *User) IsMailable() bool {
  532. return u.IsActive
  533. }
  534. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  535. if len(name) == 0 {
  536. return false, nil
  537. }
  538. return e.
  539. Where("id!=?", uid).
  540. Get(&User{LowerName: strings.ToLower(name)})
  541. }
  542. // IsUserExist checks if given user name exist,
  543. // the user name should be noncased unique.
  544. // If uid is presented, then check will rule out that one,
  545. // it is used when update a user name in settings page.
  546. func IsUserExist(uid int64, name string) (bool, error) {
  547. return isUserExist(x, uid, name)
  548. }
  549. // GetUserSalt returns a random user salt token.
  550. func GetUserSalt() (string, error) {
  551. return generate.GetRandomString(10)
  552. }
  553. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  554. func NewGhostUser() *User {
  555. return &User{
  556. ID: -1,
  557. Name: "Ghost",
  558. LowerName: "ghost",
  559. }
  560. }
  561. var (
  562. reservedUsernames = []string{
  563. "admin",
  564. "api",
  565. "assets",
  566. "avatars",
  567. "commits",
  568. "css",
  569. "debug",
  570. "error",
  571. "explore",
  572. "help",
  573. "img",
  574. "install",
  575. "issues",
  576. "js",
  577. "less",
  578. "metrics",
  579. "new",
  580. "org",
  581. "plugins",
  582. "pulls",
  583. "raw",
  584. "repo",
  585. "stars",
  586. "template",
  587. "user",
  588. "vendor",
  589. ".",
  590. "..",
  591. }
  592. reservedUserPatterns = []string{"*.keys"}
  593. )
  594. // isUsableName checks if name is reserved or pattern of name is not allowed
  595. // based on given reserved names and patterns.
  596. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  597. func isUsableName(names, patterns []string, name string) error {
  598. name = strings.TrimSpace(strings.ToLower(name))
  599. if utf8.RuneCountInString(name) == 0 {
  600. return ErrNameEmpty
  601. }
  602. for i := range names {
  603. if name == names[i] {
  604. return ErrNameReserved{name}
  605. }
  606. }
  607. for _, pat := range patterns {
  608. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  609. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  610. return ErrNamePatternNotAllowed{pat}
  611. }
  612. }
  613. return nil
  614. }
  615. // IsUsableUsername returns an error when a username is reserved
  616. func IsUsableUsername(name string) error {
  617. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  618. }
  619. // CreateUser creates record of a new user.
  620. func CreateUser(u *User) (err error) {
  621. if err = IsUsableUsername(u.Name); err != nil {
  622. return err
  623. }
  624. sess := x.NewSession()
  625. defer sess.Close()
  626. if err = sess.Begin(); err != nil {
  627. return err
  628. }
  629. isExist, err := isUserExist(sess, 0, u.Name)
  630. if err != nil {
  631. return err
  632. } else if isExist {
  633. return ErrUserAlreadyExist{u.Name}
  634. }
  635. u.Email = strings.ToLower(u.Email)
  636. isExist, err = sess.
  637. Where("email=?", u.Email).
  638. Get(new(User))
  639. if err != nil {
  640. return err
  641. } else if isExist {
  642. return ErrEmailAlreadyUsed{u.Email}
  643. }
  644. isExist, err = isEmailUsed(sess, u.Email)
  645. if err != nil {
  646. return err
  647. } else if isExist {
  648. return ErrEmailAlreadyUsed{u.Email}
  649. }
  650. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  651. u.LowerName = strings.ToLower(u.Name)
  652. u.AvatarEmail = u.Email
  653. u.Avatar = base.HashEmail(u.AvatarEmail)
  654. if u.Rands, err = GetUserSalt(); err != nil {
  655. return err
  656. }
  657. if u.Salt, err = GetUserSalt(); err != nil {
  658. return err
  659. }
  660. u.HashPassword(u.Passwd)
  661. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  662. u.MaxRepoCreation = -1
  663. if _, err = sess.Insert(u); err != nil {
  664. return err
  665. }
  666. return sess.Commit()
  667. }
  668. func countUsers(e Engine) int64 {
  669. count, _ := e.
  670. Where("type=0").
  671. Count(new(User))
  672. return count
  673. }
  674. // CountUsers returns number of users.
  675. func CountUsers() int64 {
  676. return countUsers(x)
  677. }
  678. // get user by verify code
  679. func getVerifyUser(code string) (user *User) {
  680. if len(code) <= base.TimeLimitCodeLength {
  681. return nil
  682. }
  683. // use tail hex username query user
  684. hexStr := code[base.TimeLimitCodeLength:]
  685. if b, err := hex.DecodeString(hexStr); err == nil {
  686. if user, err = GetUserByName(string(b)); user != nil {
  687. return user
  688. }
  689. log.Error(4, "user.getVerifyUser: %v", err)
  690. }
  691. return nil
  692. }
  693. // VerifyUserActiveCode verifies active code when active account
  694. func VerifyUserActiveCode(code string) (user *User) {
  695. minutes := setting.Service.ActiveCodeLives
  696. if user = getVerifyUser(code); user != nil {
  697. // time limit code
  698. prefix := code[:base.TimeLimitCodeLength]
  699. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  700. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  701. return user
  702. }
  703. }
  704. return nil
  705. }
  706. // VerifyActiveEmailCode verifies active email code when active account
  707. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  708. minutes := setting.Service.ActiveCodeLives
  709. if user := getVerifyUser(code); user != nil {
  710. // time limit code
  711. prefix := code[:base.TimeLimitCodeLength]
  712. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  713. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  714. emailAddress := &EmailAddress{Email: email}
  715. if has, _ := x.Get(emailAddress); has {
  716. return emailAddress
  717. }
  718. }
  719. }
  720. return nil
  721. }
  722. // ChangeUserName changes all corresponding setting from old user name to new one.
  723. func ChangeUserName(u *User, newUserName string) (err error) {
  724. if err = IsUsableUsername(newUserName); err != nil {
  725. return err
  726. }
  727. isExist, err := IsUserExist(0, newUserName)
  728. if err != nil {
  729. return err
  730. } else if isExist {
  731. return ErrUserAlreadyExist{newUserName}
  732. }
  733. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  734. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  735. }
  736. // Delete all local copies of repository wiki that user owns.
  737. if err = x.BufferSize(setting.IterateBufferSize).
  738. Where("owner_id=?", u.ID).
  739. Iterate(new(Repository), func(idx int, bean interface{}) error {
  740. repo := bean.(*Repository)
  741. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  742. return nil
  743. }); err != nil {
  744. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  745. }
  746. // Do not fail if directory does not exist
  747. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  748. return fmt.Errorf("Rename user directory: %v", err)
  749. }
  750. return nil
  751. }
  752. // checkDupEmail checks whether there are the same email with the user
  753. func checkDupEmail(e Engine, u *User) error {
  754. u.Email = strings.ToLower(u.Email)
  755. has, err := e.
  756. Where("id!=?", u.ID).
  757. And("type=?", u.Type).
  758. And("email=?", u.Email).
  759. Get(new(User))
  760. if err != nil {
  761. return err
  762. } else if has {
  763. return ErrEmailAlreadyUsed{u.Email}
  764. }
  765. return nil
  766. }
  767. func updateUser(e Engine, u *User) error {
  768. _, err := e.ID(u.ID).AllCols().Update(u)
  769. return err
  770. }
  771. // UpdateUser updates user's information.
  772. func UpdateUser(u *User) error {
  773. return updateUser(x, u)
  774. }
  775. // UpdateUserCols update user according special columns
  776. func UpdateUserCols(u *User, cols ...string) error {
  777. return updateUserCols(x, u, cols...)
  778. }
  779. func updateUserCols(e Engine, u *User, cols ...string) error {
  780. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  781. return err
  782. }
  783. // UpdateUserSetting updates user's settings.
  784. func UpdateUserSetting(u *User) error {
  785. if !u.IsOrganization() {
  786. if err := checkDupEmail(x, u); err != nil {
  787. return err
  788. }
  789. }
  790. return updateUser(x, u)
  791. }
  792. // deleteBeans deletes all given beans, beans should contain delete conditions.
  793. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  794. for i := range beans {
  795. if _, err = e.Delete(beans[i]); err != nil {
  796. return err
  797. }
  798. }
  799. return nil
  800. }
  801. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  802. func deleteUser(e *xorm.Session, u *User) error {
  803. // Note: A user owns any repository or belongs to any organization
  804. // cannot perform delete operation.
  805. // Check ownership of repository.
  806. count, err := getRepositoryCount(e, u)
  807. if err != nil {
  808. return fmt.Errorf("GetRepositoryCount: %v", err)
  809. } else if count > 0 {
  810. return ErrUserOwnRepos{UID: u.ID}
  811. }
  812. // Check membership of organization.
  813. count, err = u.getOrganizationCount(e)
  814. if err != nil {
  815. return fmt.Errorf("GetOrganizationCount: %v", err)
  816. } else if count > 0 {
  817. return ErrUserHasOrgs{UID: u.ID}
  818. }
  819. // ***** START: Watch *****
  820. watchedRepoIDs := make([]int64, 0, 10)
  821. if err = e.Table("watch").Cols("watch.repo_id").
  822. Where("watch.user_id = ?", u.ID).Find(&watchedRepoIDs); err != nil {
  823. return fmt.Errorf("get all watches: %v", err)
  824. }
  825. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  826. return fmt.Errorf("decrease repository num_watches: %v", err)
  827. }
  828. // ***** END: Watch *****
  829. // ***** START: Star *****
  830. starredRepoIDs := make([]int64, 0, 10)
  831. if err = e.Table("star").Cols("star.repo_id").
  832. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  833. return fmt.Errorf("get all stars: %v", err)
  834. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  835. return fmt.Errorf("decrease repository num_stars: %v", err)
  836. }
  837. // ***** END: Star *****
  838. // ***** START: Follow *****
  839. followeeIDs := make([]int64, 0, 10)
  840. if err = e.Table("follow").Cols("follow.follow_id").
  841. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  842. return fmt.Errorf("get all followees: %v", err)
  843. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  844. return fmt.Errorf("decrease user num_followers: %v", err)
  845. }
  846. followerIDs := make([]int64, 0, 10)
  847. if err = e.Table("follow").Cols("follow.user_id").
  848. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  849. return fmt.Errorf("get all followers: %v", err)
  850. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  851. return fmt.Errorf("decrease user num_following: %v", err)
  852. }
  853. // ***** END: Follow *****
  854. if err = deleteBeans(e,
  855. &AccessToken{UID: u.ID},
  856. &Collaboration{UserID: u.ID},
  857. &Access{UserID: u.ID},
  858. &Watch{UserID: u.ID},
  859. &Star{UID: u.ID},
  860. &Follow{UserID: u.ID},
  861. &Follow{FollowID: u.ID},
  862. &Action{UserID: u.ID},
  863. &IssueUser{UID: u.ID},
  864. &EmailAddress{UID: u.ID},
  865. &UserOpenID{UID: u.ID},
  866. &Reaction{UserID: u.ID},
  867. ); err != nil {
  868. return fmt.Errorf("deleteBeans: %v", err)
  869. }
  870. // ***** START: PublicKey *****
  871. keys := make([]*PublicKey, 0, 10)
  872. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  873. return fmt.Errorf("get all public keys: %v", err)
  874. }
  875. keyIDs := make([]int64, len(keys))
  876. for i := range keys {
  877. keyIDs[i] = keys[i].ID
  878. }
  879. if err = deletePublicKeys(e, keyIDs...); err != nil {
  880. return fmt.Errorf("deletePublicKeys: %v", err)
  881. }
  882. // ***** END: PublicKey *****
  883. // Clear assignee.
  884. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  885. return fmt.Errorf("clear assignee: %v", err)
  886. }
  887. // ***** START: ExternalLoginUser *****
  888. if err = removeAllAccountLinks(e, u); err != nil {
  889. return fmt.Errorf("ExternalLoginUser: %v", err)
  890. }
  891. // ***** END: ExternalLoginUser *****
  892. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  893. return fmt.Errorf("Delete: %v", err)
  894. }
  895. // FIXME: system notice
  896. // Note: There are something just cannot be roll back,
  897. // so just keep error logs of those operations.
  898. path := UserPath(u.Name)
  899. if err := os.RemoveAll(path); err != nil {
  900. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  901. }
  902. if len(u.Avatar) > 0 {
  903. avatarPath := u.CustomAvatarPath()
  904. if com.IsExist(avatarPath) {
  905. if err := os.Remove(avatarPath); err != nil {
  906. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  907. }
  908. }
  909. }
  910. return nil
  911. }
  912. // DeleteUser completely and permanently deletes everything of a user,
  913. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  914. func DeleteUser(u *User) (err error) {
  915. sess := x.NewSession()
  916. defer sess.Close()
  917. if err = sess.Begin(); err != nil {
  918. return err
  919. }
  920. if err = deleteUser(sess, u); err != nil {
  921. // Note: don't wrapper error here.
  922. return err
  923. }
  924. if err = sess.Commit(); err != nil {
  925. return err
  926. }
  927. return RewriteAllPublicKeys()
  928. }
  929. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  930. func DeleteInactivateUsers() (err error) {
  931. users := make([]*User, 0, 10)
  932. if err = x.
  933. Where("is_active = ?", false).
  934. Find(&users); err != nil {
  935. return fmt.Errorf("get all inactive users: %v", err)
  936. }
  937. // FIXME: should only update authorized_keys file once after all deletions.
  938. for _, u := range users {
  939. if err = DeleteUser(u); err != nil {
  940. // Ignore users that were set inactive by admin.
  941. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  942. continue
  943. }
  944. return err
  945. }
  946. }
  947. _, err = x.
  948. Where("is_activated = ?", false).
  949. Delete(new(EmailAddress))
  950. return err
  951. }
  952. // UserPath returns the path absolute path of user repositories.
  953. func UserPath(userName string) string {
  954. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  955. }
  956. // GetUserByKeyID get user information by user's public key id
  957. func GetUserByKeyID(keyID int64) (*User, error) {
  958. var user User
  959. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  960. Where("`public_key`.id=?", keyID).
  961. Get(&user)
  962. if err != nil {
  963. return nil, err
  964. }
  965. if !has {
  966. return nil, ErrUserNotExist{0, "", keyID}
  967. }
  968. return &user, nil
  969. }
  970. func getUserByID(e Engine, id int64) (*User, error) {
  971. u := new(User)
  972. has, err := e.ID(id).Get(u)
  973. if err != nil {
  974. return nil, err
  975. } else if !has {
  976. return nil, ErrUserNotExist{id, "", 0}
  977. }
  978. return u, nil
  979. }
  980. // GetUserByID returns the user object by given ID if exists.
  981. func GetUserByID(id int64) (*User, error) {
  982. return getUserByID(x, id)
  983. }
  984. // GetUserByName returns user by given name.
  985. func GetUserByName(name string) (*User, error) {
  986. return getUserByName(x, name)
  987. }
  988. func getUserByName(e Engine, name string) (*User, error) {
  989. if len(name) == 0 {
  990. return nil, ErrUserNotExist{0, name, 0}
  991. }
  992. u := &User{LowerName: strings.ToLower(name)}
  993. has, err := e.Get(u)
  994. if err != nil {
  995. return nil, err
  996. } else if !has {
  997. return nil, ErrUserNotExist{0, name, 0}
  998. }
  999. return u, nil
  1000. }
  1001. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  1002. func GetUserEmailsByNames(names []string) []string {
  1003. return getUserEmailsByNames(x, names)
  1004. }
  1005. func getUserEmailsByNames(e Engine, names []string) []string {
  1006. mails := make([]string, 0, len(names))
  1007. for _, name := range names {
  1008. u, err := getUserByName(e, name)
  1009. if err != nil {
  1010. continue
  1011. }
  1012. if u.IsMailable() {
  1013. mails = append(mails, u.Email)
  1014. }
  1015. }
  1016. return mails
  1017. }
  1018. // GetUsersByIDs returns all resolved users from a list of Ids.
  1019. func GetUsersByIDs(ids []int64) ([]*User, error) {
  1020. ous := make([]*User, 0, len(ids))
  1021. if len(ids) == 0 {
  1022. return ous, nil
  1023. }
  1024. err := x.In("id", ids).
  1025. Asc("name").
  1026. Find(&ous)
  1027. return ous, err
  1028. }
  1029. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1030. func GetUserIDsByNames(names []string) []int64 {
  1031. ids := make([]int64, 0, len(names))
  1032. for _, name := range names {
  1033. u, err := GetUserByName(name)
  1034. if err != nil {
  1035. continue
  1036. }
  1037. ids = append(ids, u.ID)
  1038. }
  1039. return ids
  1040. }
  1041. // UserCommit represents a commit with validation of user.
  1042. type UserCommit struct {
  1043. User *User
  1044. *git.Commit
  1045. }
  1046. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1047. func ValidateCommitWithEmail(c *git.Commit) *User {
  1048. if c.Author == nil {
  1049. return nil
  1050. }
  1051. u, err := GetUserByEmail(c.Author.Email)
  1052. if err != nil {
  1053. return nil
  1054. }
  1055. return u
  1056. }
  1057. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1058. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1059. var (
  1060. u *User
  1061. emails = map[string]*User{}
  1062. newCommits = list.New()
  1063. e = oldCommits.Front()
  1064. )
  1065. for e != nil {
  1066. c := e.Value.(*git.Commit)
  1067. if c.Author != nil {
  1068. if v, ok := emails[c.Author.Email]; !ok {
  1069. u, _ = GetUserByEmail(c.Author.Email)
  1070. emails[c.Author.Email] = u
  1071. } else {
  1072. u = v
  1073. }
  1074. } else {
  1075. u = nil
  1076. }
  1077. newCommits.PushBack(UserCommit{
  1078. User: u,
  1079. Commit: c,
  1080. })
  1081. e = e.Next()
  1082. }
  1083. return newCommits
  1084. }
  1085. // GetUserByEmail returns the user object by given e-mail if exists.
  1086. func GetUserByEmail(email string) (*User, error) {
  1087. if len(email) == 0 {
  1088. return nil, ErrUserNotExist{0, email, 0}
  1089. }
  1090. email = strings.ToLower(email)
  1091. // First try to find the user by primary email
  1092. user := &User{Email: email}
  1093. has, err := x.Get(user)
  1094. if err != nil {
  1095. return nil, err
  1096. }
  1097. if has {
  1098. return user, nil
  1099. }
  1100. // Otherwise, check in alternative list for activated email addresses
  1101. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1102. has, err = x.Get(emailAddress)
  1103. if err != nil {
  1104. return nil, err
  1105. }
  1106. if has {
  1107. return GetUserByID(emailAddress.UID)
  1108. }
  1109. return nil, ErrUserNotExist{0, email, 0}
  1110. }
  1111. // GetUser checks if a user already exists
  1112. func GetUser(user *User) (bool, error) {
  1113. return x.Get(user)
  1114. }
  1115. // SearchUserOptions contains the options for searching
  1116. type SearchUserOptions struct {
  1117. Keyword string
  1118. Type UserType
  1119. UID int64
  1120. OrderBy SearchOrderBy
  1121. Page int
  1122. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1123. IsActive util.OptionalBool
  1124. SearchByEmail bool // Search by email as well as username/full name
  1125. }
  1126. func (opts *SearchUserOptions) toConds() builder.Cond {
  1127. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1128. if len(opts.Keyword) > 0 {
  1129. lowerKeyword := strings.ToLower(opts.Keyword)
  1130. keywordCond := builder.Or(
  1131. builder.Like{"lower_name", lowerKeyword},
  1132. builder.Like{"LOWER(full_name)", lowerKeyword},
  1133. )
  1134. if opts.SearchByEmail {
  1135. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1136. }
  1137. cond = cond.And(keywordCond)
  1138. }
  1139. if opts.UID > 0 {
  1140. cond = cond.And(builder.Eq{"id": opts.UID})
  1141. }
  1142. if !opts.IsActive.IsNone() {
  1143. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1144. }
  1145. return cond
  1146. }
  1147. // SearchUsers takes options i.e. keyword and part of user name to search,
  1148. // it returns results in given range and number of total results.
  1149. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1150. cond := opts.toConds()
  1151. count, err := x.Where(cond).Count(new(User))
  1152. if err != nil {
  1153. return nil, 0, fmt.Errorf("Count: %v", err)
  1154. }
  1155. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1156. opts.PageSize = setting.UI.ExplorePagingNum
  1157. }
  1158. if opts.Page <= 0 {
  1159. opts.Page = 1
  1160. }
  1161. if len(opts.OrderBy) == 0 {
  1162. opts.OrderBy = SearchOrderByAlphabetically
  1163. }
  1164. users = make([]*User, 0, opts.PageSize)
  1165. return users, count, x.Where(cond).
  1166. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  1167. OrderBy(opts.OrderBy.String()).
  1168. Find(&users)
  1169. }
  1170. // GetStarredRepos returns the repos starred by a particular user
  1171. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1172. sess := x.Where("star.uid=?", userID).
  1173. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1174. if !private {
  1175. sess = sess.And("is_private=?", false)
  1176. }
  1177. repos := make([]*Repository, 0, 10)
  1178. err := sess.Find(&repos)
  1179. if err != nil {
  1180. return nil, err
  1181. }
  1182. return repos, nil
  1183. }
  1184. // GetWatchedRepos returns the repos watched by a particular user
  1185. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1186. sess := x.Where("watch.user_id=?", userID).
  1187. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1188. if !private {
  1189. sess = sess.And("is_private=?", false)
  1190. }
  1191. repos := make([]*Repository, 0, 10)
  1192. err := sess.Find(&repos)
  1193. if err != nil {
  1194. return nil, err
  1195. }
  1196. return repos, nil
  1197. }
  1198. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1199. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1200. // Start session
  1201. sess := x.NewSession()
  1202. defer sess.Close()
  1203. if err := sess.Begin(); err != nil {
  1204. return false, err
  1205. }
  1206. // Delete keys marked for deletion
  1207. var sshKeysNeedUpdate bool
  1208. for _, KeyToDelete := range keys {
  1209. key, err := SearchPublicKeyByContent(KeyToDelete)
  1210. if err != nil {
  1211. log.Error(4, "SearchPublicKeyByContent: %v", err)
  1212. continue
  1213. }
  1214. if err = deletePublicKeys(sess, key.ID); err != nil {
  1215. log.Error(4, "deletePublicKeys: %v", err)
  1216. continue
  1217. }
  1218. sshKeysNeedUpdate = true
  1219. }
  1220. if err := sess.Commit(); err != nil {
  1221. return false, err
  1222. }
  1223. return sshKeysNeedUpdate, nil
  1224. }
  1225. func addLdapSSHPublicKeys(s *LoginSource, usr *User, SSHPublicKeys []string) bool {
  1226. var sshKeysNeedUpdate bool
  1227. for _, sshKey := range SSHPublicKeys {
  1228. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1229. if err == nil {
  1230. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1231. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1232. log.Error(4, "addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1233. } else {
  1234. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1235. sshKeysNeedUpdate = true
  1236. }
  1237. } else {
  1238. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1239. }
  1240. }
  1241. return sshKeysNeedUpdate
  1242. }
  1243. func synchronizeLdapSSHPublicKeys(s *LoginSource, SSHPublicKeys []string, usr *User) bool {
  1244. var sshKeysNeedUpdate bool
  1245. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1246. // Get Public Keys from DB with current LDAP source
  1247. var giteaKeys []string
  1248. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1249. if err != nil {
  1250. log.Error(4, "synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1251. }
  1252. for _, v := range keys {
  1253. giteaKeys = append(giteaKeys, v.OmitEmail())
  1254. }
  1255. // Get Public Keys from LDAP and skip duplicate keys
  1256. var ldapKeys []string
  1257. for _, v := range SSHPublicKeys {
  1258. ldapKey := strings.Join(strings.Split(v, " ")[:2], " ")
  1259. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1260. ldapKeys = append(ldapKeys, ldapKey)
  1261. }
  1262. }
  1263. // Check if Public Key sync is needed
  1264. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1265. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Keys are already in sync for %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1266. return false
  1267. }
  1268. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1269. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1270. var newLdapSSHKeys []string
  1271. for _, LDAPPublicSSHKey := range ldapKeys {
  1272. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1273. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1274. }
  1275. }
  1276. if addLdapSSHPublicKeys(s, usr, newLdapSSHKeys) {
  1277. sshKeysNeedUpdate = true
  1278. }
  1279. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1280. var giteaKeysToDelete []string
  1281. for _, giteaKey := range giteaKeys {
  1282. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1283. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1284. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1285. }
  1286. }
  1287. // Delete LDAP keys from DB that doesn't exist in LDAP
  1288. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1289. if err != nil {
  1290. log.Error(4, "synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1291. }
  1292. if needUpd {
  1293. sshKeysNeedUpdate = true
  1294. }
  1295. return sshKeysNeedUpdate
  1296. }
  1297. // SyncExternalUsers is used to synchronize users with external authorization source
  1298. func SyncExternalUsers() {
  1299. if !taskStatusTable.StartIfNotRunning(syncExternalUsers) {
  1300. return
  1301. }
  1302. defer taskStatusTable.Stop(syncExternalUsers)
  1303. log.Trace("Doing: SyncExternalUsers")
  1304. ls, err := LoginSources()
  1305. if err != nil {
  1306. log.Error(4, "SyncExternalUsers: %v", err)
  1307. return
  1308. }
  1309. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1310. for _, s := range ls {
  1311. if !s.IsActived || !s.IsSyncEnabled {
  1312. continue
  1313. }
  1314. if s.IsLDAP() {
  1315. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1316. var existingUsers []int64
  1317. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1318. var sshKeysNeedUpdate bool
  1319. // Find all users with this login type
  1320. var users []User
  1321. x.Where("login_type = ?", LoginLDAP).
  1322. And("login_source = ?", s.ID).
  1323. Find(&users)
  1324. sr := s.LDAP().SearchEntries()
  1325. for _, su := range sr {
  1326. if len(su.Username) == 0 {
  1327. continue
  1328. }
  1329. if len(su.Mail) == 0 {
  1330. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1331. }
  1332. var usr *User
  1333. // Search for existing user
  1334. for _, du := range users {
  1335. if du.LowerName == strings.ToLower(su.Username) {
  1336. usr = &du
  1337. break
  1338. }
  1339. }
  1340. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1341. // If no existing user found, create one
  1342. if usr == nil {
  1343. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1344. usr = &User{
  1345. LowerName: strings.ToLower(su.Username),
  1346. Name: su.Username,
  1347. FullName: fullName,
  1348. LoginType: s.Type,
  1349. LoginSource: s.ID,
  1350. LoginName: su.Username,
  1351. Email: su.Mail,
  1352. IsAdmin: su.IsAdmin,
  1353. IsActive: true,
  1354. }
  1355. err = CreateUser(usr)
  1356. if err != nil {
  1357. log.Error(4, "SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1358. } else if isAttributeSSHPublicKeySet {
  1359. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1360. if addLdapSSHPublicKeys(s, usr, su.SSHPublicKey) {
  1361. sshKeysNeedUpdate = true
  1362. }
  1363. }
  1364. } else if updateExisting {
  1365. existingUsers = append(existingUsers, usr.ID)
  1366. // Synchronize SSH Public Key if that attribute is set
  1367. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(s, su.SSHPublicKey, usr) {
  1368. sshKeysNeedUpdate = true
  1369. }
  1370. // Check if user data has changed
  1371. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1372. strings.ToLower(usr.Email) != strings.ToLower(su.Mail) ||
  1373. usr.FullName != fullName ||
  1374. !usr.IsActive {
  1375. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1376. usr.FullName = fullName
  1377. usr.Email = su.Mail
  1378. // Change existing admin flag only if AdminFilter option is set
  1379. if len(s.LDAP().AdminFilter) > 0 {
  1380. usr.IsAdmin = su.IsAdmin
  1381. }
  1382. usr.IsActive = true
  1383. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1384. if err != nil {
  1385. log.Error(4, "SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1386. }
  1387. }
  1388. }
  1389. }
  1390. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1391. if sshKeysNeedUpdate {
  1392. RewriteAllPublicKeys()
  1393. }
  1394. // Deactivate users not present in LDAP
  1395. if updateExisting {
  1396. for _, usr := range users {
  1397. found := false
  1398. for _, uid := range existingUsers {
  1399. if usr.ID == uid {
  1400. found = true
  1401. break
  1402. }
  1403. }
  1404. if !found {
  1405. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1406. usr.IsActive = false
  1407. err = UpdateUserCols(&usr, "is_active")
  1408. if err != nil {
  1409. log.Error(4, "SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1410. }
  1411. }
  1412. }
  1413. }
  1414. }
  1415. }
  1416. }