user.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. package models
  2. import (
  3. "bytes"
  4. "container/list"
  5. "crypto/sha256"
  6. "crypto/subtle"
  7. "encoding/hex"
  8. "fmt"
  9. "gitote/gitote/models/errors"
  10. "gitote/gitote/pkg/avatar"
  11. "gitote/gitote/pkg/setting"
  12. "gitote/gitote/pkg/tool"
  13. "image"
  14. _ "image/jpeg"
  15. "image/png"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. "time"
  20. "unicode/utf8"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/xorm"
  23. "github.com/nfnt/resize"
  24. "gitlab.com/gitote/git-module"
  25. api "gitlab.com/gitote/go-gitote-client"
  26. "golang.org/x/crypto/pbkdf2"
  27. log "gopkg.in/clog.v1"
  28. )
  29. // USER_AVATAR_URL_PREFIX is used to identify a URL is to access user avatar.
  30. const USER_AVATAR_URL_PREFIX = "avatars"
  31. type UserType int
  32. const (
  33. USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  34. USER_TYPE_ORGANIZATION
  35. )
  36. // User represents the object of individual and member of organization.
  37. type User struct {
  38. ID int64
  39. LowerName string `xorm:"UNIQUE NOT NULL"`
  40. Name string `xorm:"UNIQUE NOT NULL"`
  41. FullName string
  42. Company string
  43. // Email is the primary email address (to be used for communication)
  44. Email string `xorm:"NOT NULL"`
  45. Passwd string `xorm:"NOT NULL"`
  46. LoginType LoginType
  47. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  48. LoginName string
  49. Type UserType
  50. OwnedOrgs []*User `xorm:"-" json:"-"`
  51. Orgs []*User `xorm:"-" json:"-"`
  52. Repos []*Repository `xorm:"-" json:"-"`
  53. Location string
  54. Website string
  55. ThemeColor string
  56. Rands string `xorm:"VARCHAR(10)"`
  57. Salt string `xorm:"VARCHAR(10)"`
  58. Created time.Time `xorm:"-" json:"-"`
  59. CreatedUnix int64
  60. Updated time.Time `xorm:"-" json:"-"`
  61. UpdatedUnix int64
  62. // Remember visibility choice for convenience, true for private
  63. LastRepoVisibility bool
  64. // Maximum repository creation limit, -1 means use global default
  65. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  66. // Permissions
  67. IsActive bool // Activate primary email
  68. IsBeta bool
  69. ShowSponsors bool
  70. IsStaff bool
  71. IsIntern bool
  72. IsAdmin bool
  73. AllowGitHook bool
  74. AllowImportLocal bool // Allow migrate repository by local path
  75. ProhibitLogin bool
  76. // Badges
  77. IsVerified bool
  78. IsMaker bool
  79. IsBugHunter bool
  80. // Social
  81. Twitter string
  82. Linkedin string
  83. Github string
  84. Devto string
  85. Stackoverflow string
  86. Reddit string
  87. Telegram string
  88. Codepen string
  89. // Avatar
  90. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  91. AvatarEmail string `xorm:"NOT NULL"`
  92. UseCustomAvatar bool
  93. // Counters
  94. NumFollowers int
  95. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  96. NumStars int
  97. NumRepos int
  98. // For organization
  99. Description string
  100. NumTeams int
  101. NumMembers int
  102. Teams []*Team `xorm:"-" json:"-"`
  103. Members []*User `xorm:"-" json:"-"`
  104. // For Admins
  105. StaffNotes string
  106. // Certificate
  107. Recognized string
  108. Certified string
  109. }
  110. func (u *User) BeforeInsert() {
  111. u.CreatedUnix = time.Now().Unix()
  112. u.UpdatedUnix = u.CreatedUnix
  113. }
  114. func (u *User) BeforeUpdate() {
  115. if u.MaxRepoCreation < -1 {
  116. u.MaxRepoCreation = -1
  117. }
  118. u.UpdatedUnix = time.Now().Unix()
  119. }
  120. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  121. switch colName {
  122. case "created_unix":
  123. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  124. case "updated_unix":
  125. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  126. }
  127. }
  128. // IDStr returns string representation of user's ID.
  129. func (u *User) IDStr() string {
  130. return com.ToStr(u.ID)
  131. }
  132. func (u *User) APIFormat() *api.User {
  133. return &api.User{
  134. ID: u.ID,
  135. UserName: u.Name,
  136. FullName: u.FullName,
  137. Website: u.Website,
  138. Company: u.Company,
  139. Location: u.Location,
  140. Description: u.Description,
  141. Email: u.Email,
  142. IsAdmin: u.IsAdmin,
  143. NumRepos: u.NumRepos,
  144. Created: u.Created,
  145. Updated: u.Updated,
  146. NumFollowing: u.NumFollowing,
  147. NumFollowers: u.NumFollowers,
  148. AvatarUrl: u.AvatarLink(),
  149. }
  150. }
  151. // returns true if user login type is LOGIN_PLAIN.
  152. func (u *User) IsLocal() bool {
  153. return u.LoginType <= LOGIN_PLAIN
  154. }
  155. // HasForkedRepo checks if user has already forked a repository with given ID.
  156. func (u *User) HasForkedRepo(repoID int64) bool {
  157. _, has, _ := HasForkedRepo(u.ID, repoID)
  158. return has
  159. }
  160. func (u *User) RepoCreationNum() int {
  161. if u.MaxRepoCreation <= -1 {
  162. return setting.Repository.MaxCreationLimit
  163. }
  164. return u.MaxRepoCreation
  165. }
  166. func (u *User) CanCreateRepo() bool {
  167. if u.MaxRepoCreation <= -1 {
  168. if setting.Repository.MaxCreationLimit <= -1 {
  169. return true
  170. }
  171. return u.NumRepos < setting.Repository.MaxCreationLimit
  172. }
  173. return u.NumRepos < u.MaxRepoCreation
  174. }
  175. func (u *User) CanCreateOrganization() bool {
  176. return !setting.Admin.DisableRegularOrgCreation || u.IsAdmin
  177. }
  178. // CanEditGitHook returns true if user can edit Git hooks.
  179. func (u *User) CanEditGitHook() bool {
  180. return u.IsAdmin || u.AllowGitHook
  181. }
  182. // CanImportLocal returns true if user can migrate repository by local path.
  183. func (u *User) CanImportLocal() bool {
  184. return setting.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  185. }
  186. // DashboardLink returns the user dashboard page link.
  187. func (u *User) DashboardLink() string {
  188. if u.IsOrganization() {
  189. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  190. }
  191. return setting.AppSubURL + "/"
  192. }
  193. // HomeLink returns the user or organization home page link.
  194. func (u *User) HomeLink() string {
  195. return setting.AppSubURL + "/" + u.Name
  196. }
  197. func (u *User) HTMLURL() string {
  198. return setting.AppURL + u.Name
  199. }
  200. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  201. func (u *User) GenerateEmailActivateCode(email string) string {
  202. code := tool.CreateTimeLimitCode(
  203. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  204. setting.Service.ActiveCodeLives, nil)
  205. // Add tail hex username
  206. code += hex.EncodeToString([]byte(u.LowerName))
  207. return code
  208. }
  209. // GenerateActivateCode generates an activate code based on user information.
  210. func (u *User) GenerateActivateCode() string {
  211. return u.GenerateEmailActivateCode(u.Email)
  212. }
  213. // CustomAvatarPath returns user custom avatar file path.
  214. func (u *User) CustomAvatarPath() string {
  215. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.ID))
  216. }
  217. // GenerateRandomAvatar generates a random avatar for user.
  218. func (u *User) GenerateRandomAvatar() error {
  219. seed := u.Email
  220. if len(seed) == 0 {
  221. seed = u.Name
  222. }
  223. img, err := avatar.RandomImage([]byte(seed))
  224. if err != nil {
  225. return fmt.Errorf("RandomImage: %v", err)
  226. }
  227. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  228. return fmt.Errorf("MkdirAll: %v", err)
  229. }
  230. fw, err := os.Create(u.CustomAvatarPath())
  231. if err != nil {
  232. return fmt.Errorf("Create: %v", err)
  233. }
  234. defer fw.Close()
  235. if err = png.Encode(fw, img); err != nil {
  236. return fmt.Errorf("Encode: %v", err)
  237. }
  238. log.Info("New random avatar created: %d", u.ID)
  239. return nil
  240. }
  241. // RelAvatarLink returns relative avatar link to the site domain,
  242. // which includes app sub-url as prefix. However, it is possible
  243. // to return full URL if user enables Gravatar-like service.
  244. func (u *User) RelAvatarLink() string {
  245. defaultImgUrl := "https://cdn.jsdelivr.net/npm/gitote@1.0.1/img/avatar_default.png"
  246. if u.ID == -1 {
  247. return defaultImgUrl
  248. }
  249. switch {
  250. case u.UseCustomAvatar:
  251. if !com.IsExist(u.CustomAvatarPath()) {
  252. return defaultImgUrl
  253. }
  254. return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, USER_AVATAR_URL_PREFIX, u.ID)
  255. case setting.DisableGravatar, setting.OfflineMode:
  256. if !com.IsExist(u.CustomAvatarPath()) {
  257. if err := u.GenerateRandomAvatar(); err != nil {
  258. log.Error(3, "GenerateRandomAvatar: %v", err)
  259. }
  260. }
  261. return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, USER_AVATAR_URL_PREFIX, u.ID)
  262. }
  263. return tool.AvatarLink(u.AvatarEmail)
  264. }
  265. // AvatarLink returns user avatar absolute link.
  266. func (u *User) AvatarLink() string {
  267. link := u.RelAvatarLink()
  268. if link[0] == '/' && link[1] != '/' {
  269. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  270. }
  271. return link
  272. }
  273. // User.GetFollwoers returns range of user's followers.
  274. func (u *User) GetFollowers(page int) ([]*User, error) {
  275. users := make([]*User, 0, ItemsPerPage)
  276. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.follow_id=?", u.ID)
  277. if setting.UsePostgreSQL {
  278. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  279. } else {
  280. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  281. }
  282. return users, sess.Find(&users)
  283. }
  284. func (u *User) IsFollowing(followID int64) bool {
  285. return IsFollowing(u.ID, followID)
  286. }
  287. // GetFollowing returns range of user's following.
  288. func (u *User) GetFollowing(page int) ([]*User, error) {
  289. users := make([]*User, 0, ItemsPerPage)
  290. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.user_id=?", u.ID)
  291. if setting.UsePostgreSQL {
  292. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  293. } else {
  294. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  295. }
  296. return users, sess.Find(&users)
  297. }
  298. // NewGitSig generates and returns the signature of given user.
  299. func (u *User) NewGitSig() *git.Signature {
  300. return &git.Signature{
  301. Name: u.DisplayName(),
  302. Email: u.Email,
  303. When: time.Now(),
  304. }
  305. }
  306. // EncodePasswd encodes password to safe format.
  307. func (u *User) EncodePasswd() {
  308. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  309. u.Passwd = fmt.Sprintf("%x", newPasswd)
  310. }
  311. // ValidatePassword checks if given password matches the one belongs to the user.
  312. func (u *User) ValidatePassword(passwd string) bool {
  313. newUser := &User{Passwd: passwd, Salt: u.Salt}
  314. newUser.EncodePasswd()
  315. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  316. }
  317. // UploadAvatar saves custom avatar for user.
  318. // FIXME: split uploads to different subdirs in case we have massive number of users.
  319. func (u *User) UploadAvatar(data []byte) error {
  320. img, _, err := image.Decode(bytes.NewReader(data))
  321. if err != nil {
  322. return fmt.Errorf("decode image: %v", err)
  323. }
  324. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  325. fw, err := os.Create(u.CustomAvatarPath())
  326. if err != nil {
  327. return fmt.Errorf("create custom avatar directory: %v", err)
  328. }
  329. defer fw.Close()
  330. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  331. if err = png.Encode(fw, m); err != nil {
  332. return fmt.Errorf("encode image: %v", err)
  333. }
  334. return nil
  335. }
  336. // DeleteAvatar deletes the user's custom avatar.
  337. func (u *User) DeleteAvatar() error {
  338. log.Trace("DeleteAvatar [%d]: %s", u.ID, u.CustomAvatarPath())
  339. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  340. return err
  341. }
  342. u.UseCustomAvatar = false
  343. return UpdateUser(u)
  344. }
  345. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  346. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  347. has, err := HasAccess(u.ID, repo, ACCESS_MODE_ADMIN)
  348. if err != nil {
  349. log.Error(2, "HasAccess: %v", err)
  350. }
  351. return has
  352. }
  353. // IsWriterOfRepo returns true if user has write access to given repository.
  354. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  355. has, err := HasAccess(u.ID, repo, ACCESS_MODE_WRITE)
  356. if err != nil {
  357. log.Error(2, "HasAccess: %v", err)
  358. }
  359. return has
  360. }
  361. // IsOrganization returns true if user is actually a organization.
  362. func (u *User) IsOrganization() bool {
  363. return u.Type == USER_TYPE_ORGANIZATION
  364. }
  365. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  366. func (u *User) IsUserOrgOwner(orgId int64) bool {
  367. return IsOrganizationOwner(orgId, u.ID)
  368. }
  369. // IsPublicMember returns true if user public his/her membership in give organization.
  370. func (u *User) IsPublicMember(orgId int64) bool {
  371. return IsPublicMembership(orgId, u.ID)
  372. }
  373. // IsEnabledTwoFactor returns true if user has enabled two-factor authentication.
  374. func (u *User) IsEnabledTwoFactor() bool {
  375. return IsUserEnabledTwoFactor(u.ID)
  376. }
  377. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  378. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  379. }
  380. // GetOrganizationCount returns count of membership of organization of user.
  381. func (u *User) GetOrganizationCount() (int64, error) {
  382. return u.getOrganizationCount(x)
  383. }
  384. // GetRepositories returns repositories that user owns, including private repositories.
  385. func (u *User) GetRepositories(page, pageSize int) (err error) {
  386. u.Repos, err = GetUserRepositories(&UserRepoOptions{
  387. UserID: u.ID,
  388. Private: true,
  389. Page: page,
  390. PageSize: pageSize,
  391. })
  392. return err
  393. }
  394. // GetRepositories returns mirror repositories that user owns, including private repositories.
  395. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  396. return GetUserMirrorRepositories(u.ID)
  397. }
  398. // GetOwnedOrganizations returns all organizations that user owns.
  399. func (u *User) GetOwnedOrganizations() (err error) {
  400. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  401. return err
  402. }
  403. // GetOrganizations returns all organizations that user belongs to.
  404. func (u *User) GetOrganizations(showPrivate bool) error {
  405. orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
  406. if err != nil {
  407. return fmt.Errorf("GetOrgIDsByUserID: %v", err)
  408. }
  409. if len(orgIDs) == 0 {
  410. return nil
  411. }
  412. u.Orgs = make([]*User, 0, len(orgIDs))
  413. if err = x.Where("type = ?", USER_TYPE_ORGANIZATION).In("id", orgIDs).Find(&u.Orgs); err != nil {
  414. return err
  415. }
  416. return nil
  417. }
  418. // DisplayName returns full name if it's not empty,
  419. // returns username otherwise.
  420. func (u *User) DisplayName() string {
  421. if len(u.FullName) > 0 {
  422. return u.FullName
  423. }
  424. return u.Name
  425. }
  426. func (u *User) ShortName(length int) string {
  427. return tool.EllipsisString(u.Name, length)
  428. }
  429. // IsMailable checks if a user is elegible
  430. // to receive emails.
  431. func (u *User) IsMailable() bool {
  432. return u.IsActive
  433. }
  434. // IsUserExist checks if given user name exist,
  435. // the user name should be noncased unique.
  436. // If uid is presented, then check will rule out that one,
  437. // it is used when update a user name in settings page.
  438. func IsUserExist(uid int64, name string) (bool, error) {
  439. if len(name) == 0 {
  440. return false, nil
  441. }
  442. return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
  443. }
  444. // GetUserSalt returns a ramdom user salt token.
  445. func GetUserSalt() (string, error) {
  446. return tool.RandomString(10)
  447. }
  448. // NewGhostUser creates and returns a fake user for someone who has deleted his/her account.
  449. func NewGhostUser() *User {
  450. return &User{
  451. ID: -1,
  452. Name: "Ghost",
  453. LowerName: "ghost",
  454. }
  455. }
  456. var (
  457. reservedUsernames = []string{"explore", "create", "assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", "pages", "about", "privacy", "faq", "tos", "status", "developers", "brand", "contact", "heartbeat", "verified", "contribute", "status", "blog", "maker", "brand", "jobs", "features", "makers", "features", "request", ".", ".."}
  458. reservedUserPatterns = []string{"*.keys"}
  459. )
  460. // isUsableName checks if name is reserved or pattern of name is not allowed
  461. // based on given reserved names and patterns.
  462. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  463. func isUsableName(names, patterns []string, name string) error {
  464. name = strings.TrimSpace(strings.ToLower(name))
  465. if utf8.RuneCountInString(name) == 0 {
  466. return errors.EmptyName{}
  467. }
  468. for i := range names {
  469. if name == names[i] {
  470. return ErrNameReserved{name}
  471. }
  472. }
  473. for _, pat := range patterns {
  474. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  475. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  476. return ErrNamePatternNotAllowed{pat}
  477. }
  478. }
  479. return nil
  480. }
  481. func IsUsableUsername(name string) error {
  482. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  483. }
  484. // CreateUser creates record of a new user.
  485. func CreateUser(u *User) (err error) {
  486. if err = IsUsableUsername(u.Name); err != nil {
  487. return err
  488. }
  489. isExist, err := IsUserExist(0, u.Name)
  490. if err != nil {
  491. return err
  492. } else if isExist {
  493. return ErrUserAlreadyExist{u.Name}
  494. }
  495. u.Email = strings.ToLower(u.Email)
  496. isExist, err = IsEmailUsed(u.Email)
  497. if err != nil {
  498. return err
  499. } else if isExist {
  500. return ErrEmailAlreadyUsed{u.Email}
  501. }
  502. u.LowerName = strings.ToLower(u.Name)
  503. u.AvatarEmail = u.Email
  504. u.Avatar = tool.HashEmail(u.AvatarEmail)
  505. if u.Rands, err = GetUserSalt(); err != nil {
  506. return err
  507. }
  508. if u.Salt, err = GetUserSalt(); err != nil {
  509. return err
  510. }
  511. u.EncodePasswd()
  512. u.MaxRepoCreation = -1
  513. sess := x.NewSession()
  514. defer sess.Close()
  515. if err = sess.Begin(); err != nil {
  516. return err
  517. }
  518. if _, err = sess.Insert(u); err != nil {
  519. return err
  520. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  521. return err
  522. }
  523. return sess.Commit()
  524. }
  525. func countUsers(e Engine) int64 {
  526. count, _ := e.Where("type=0").Count(new(User))
  527. return count
  528. }
  529. // CountUsers returns number of users.
  530. func CountUsers() int64 {
  531. return countUsers(x)
  532. }
  533. // Users returns number of users in given page.
  534. func Users(page, pageSize int) ([]*User, error) {
  535. users := make([]*User, 0, pageSize)
  536. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  537. }
  538. // parseUserFromCode returns user by username encoded in code.
  539. // It returns nil if code or username is invalid.
  540. func parseUserFromCode(code string) (user *User) {
  541. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  542. return nil
  543. }
  544. // Use tail hex username to query user
  545. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  546. if b, err := hex.DecodeString(hexStr); err == nil {
  547. if user, err = GetUserByName(string(b)); user != nil {
  548. return user
  549. } else if !errors.IsUserNotExist(err) {
  550. log.Error(2, "GetUserByName: %v", err)
  551. }
  552. }
  553. return nil
  554. }
  555. // verify active code when active account
  556. func VerifyUserActiveCode(code string) (user *User) {
  557. minutes := setting.Service.ActiveCodeLives
  558. if user = parseUserFromCode(code); user != nil {
  559. // time limit code
  560. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  561. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  562. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  563. return user
  564. }
  565. }
  566. return nil
  567. }
  568. // verify active code when active account
  569. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  570. minutes := setting.Service.ActiveCodeLives
  571. if user := parseUserFromCode(code); user != nil {
  572. // time limit code
  573. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  574. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  575. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  576. emailAddress := &EmailAddress{Email: email}
  577. if has, _ := x.Get(emailAddress); has {
  578. return emailAddress
  579. }
  580. }
  581. }
  582. return nil
  583. }
  584. // ChangeUserName changes all corresponding setting from old user name to new one.
  585. func ChangeUserName(u *User, newUserName string) (err error) {
  586. if err = IsUsableUsername(newUserName); err != nil {
  587. return err
  588. }
  589. isExist, err := IsUserExist(0, newUserName)
  590. if err != nil {
  591. return err
  592. } else if isExist {
  593. return ErrUserAlreadyExist{newUserName}
  594. }
  595. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  596. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  597. }
  598. // Delete all local copies of repository wiki that user owns.
  599. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  600. repo := bean.(*Repository)
  601. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  602. return nil
  603. }); err != nil {
  604. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  605. }
  606. // Rename or create user base directory
  607. baseDir := UserPath(u.Name)
  608. newBaseDir := UserPath(newUserName)
  609. if com.IsExist(baseDir) {
  610. return os.Rename(baseDir, newBaseDir)
  611. }
  612. return os.MkdirAll(newBaseDir, os.ModePerm)
  613. }
  614. func updateUser(e Engine, u *User) error {
  615. // Organization does not need email
  616. if !u.IsOrganization() {
  617. u.Email = strings.ToLower(u.Email)
  618. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  619. if err != nil {
  620. return err
  621. } else if has {
  622. return ErrEmailAlreadyUsed{u.Email}
  623. }
  624. if len(u.AvatarEmail) == 0 {
  625. u.AvatarEmail = u.Email
  626. }
  627. u.Avatar = tool.HashEmail(u.AvatarEmail)
  628. }
  629. if len(u.Description) > 255 {
  630. u.Description = u.Description[:255]
  631. }
  632. u.LowerName = strings.ToLower(u.Name)
  633. u.Company = tool.TruncateString(u.Company, 255)
  634. u.Location = tool.TruncateString(u.Location, 255)
  635. u.Website = tool.TruncateString(u.Website, 255)
  636. _, err := e.ID(u.ID).AllCols().Update(u)
  637. return err
  638. }
  639. // UpdateUser updates user's information.
  640. func UpdateUser(u *User) error {
  641. return updateUser(x, u)
  642. }
  643. // deleteBeans deletes all given beans, beans should contain delete conditions.
  644. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  645. for i := range beans {
  646. if _, err = e.Delete(beans[i]); err != nil {
  647. return err
  648. }
  649. }
  650. return nil
  651. }
  652. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  653. func deleteUser(e *xorm.Session, u *User) error {
  654. // Note: A user owns any repository or belongs to any organization
  655. // cannot perform delete operation.
  656. // Check ownership of repository.
  657. count, err := getRepositoryCount(e, u)
  658. if err != nil {
  659. return fmt.Errorf("GetRepositoryCount: %v", err)
  660. } else if count > 0 {
  661. return ErrUserOwnRepos{UID: u.ID}
  662. }
  663. // Check membership of organization.
  664. count, err = u.getOrganizationCount(e)
  665. if err != nil {
  666. return fmt.Errorf("GetOrganizationCount: %v", err)
  667. } else if count > 0 {
  668. return ErrUserHasOrgs{UID: u.ID}
  669. }
  670. // ***** START: Watch *****
  671. watches := make([]*Watch, 0, 10)
  672. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  673. return fmt.Errorf("get all watches: %v", err)
  674. }
  675. for i := range watches {
  676. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  677. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  678. }
  679. }
  680. // ***** END: Watch *****
  681. // ***** START: Star *****
  682. stars := make([]*Star, 0, 10)
  683. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  684. return fmt.Errorf("get all stars: %v", err)
  685. }
  686. for i := range stars {
  687. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  688. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  689. }
  690. }
  691. // ***** END: Star *****
  692. // ***** START: Follow *****
  693. followers := make([]*Follow, 0, 10)
  694. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  695. return fmt.Errorf("get all followers: %v", err)
  696. }
  697. for i := range followers {
  698. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  699. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  700. }
  701. }
  702. // ***** END: Follow *****
  703. if err = deleteBeans(e,
  704. &AccessToken{UID: u.ID},
  705. &Collaboration{UserID: u.ID},
  706. &Access{UserID: u.ID},
  707. &Watch{UserID: u.ID},
  708. &Star{UID: u.ID},
  709. &Follow{FollowID: u.ID},
  710. &Action{UserID: u.ID},
  711. &IssueUser{UID: u.ID},
  712. &EmailAddress{UID: u.ID},
  713. ); err != nil {
  714. return fmt.Errorf("deleteBeans: %v", err)
  715. }
  716. // ***** START: PublicKey *****
  717. keys := make([]*PublicKey, 0, 10)
  718. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  719. return fmt.Errorf("get all public keys: %v", err)
  720. }
  721. keyIDs := make([]int64, len(keys))
  722. for i := range keys {
  723. keyIDs[i] = keys[i].ID
  724. }
  725. if err = deletePublicKeys(e, keyIDs...); err != nil {
  726. return fmt.Errorf("deletePublicKeys: %v", err)
  727. }
  728. // ***** END: PublicKey *****
  729. // Clear assignee.
  730. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  731. return fmt.Errorf("clear assignee: %v", err)
  732. }
  733. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  734. return fmt.Errorf("Delete: %v", err)
  735. }
  736. // FIXME: system notice
  737. // Note: There are something just cannot be roll back,
  738. // so just keep error logs of those operations.
  739. os.RemoveAll(UserPath(u.Name))
  740. os.Remove(u.CustomAvatarPath())
  741. return nil
  742. }
  743. // DeleteUser completely and permanently deletes everything of a user,
  744. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  745. func DeleteUser(u *User) (err error) {
  746. sess := x.NewSession()
  747. defer sess.Close()
  748. if err = sess.Begin(); err != nil {
  749. return err
  750. }
  751. if err = deleteUser(sess, u); err != nil {
  752. // Note: don't wrapper error here.
  753. return err
  754. }
  755. if err = sess.Commit(); err != nil {
  756. return err
  757. }
  758. return RewriteAuthorizedKeys()
  759. }
  760. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  761. func DeleteInactivateUsers() (err error) {
  762. users := make([]*User, 0, 10)
  763. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  764. return fmt.Errorf("get all inactive users: %v", err)
  765. }
  766. // FIXME: should only update authorized_keys file once after all deletions.
  767. for _, u := range users {
  768. if err = DeleteUser(u); err != nil {
  769. // Ignore users that were set inactive by admin.
  770. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  771. continue
  772. }
  773. return err
  774. }
  775. }
  776. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  777. return err
  778. }
  779. // UserPath returns the path absolute path of user repositories.
  780. func UserPath(userName string) string {
  781. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  782. }
  783. func GetUserByKeyID(keyID int64) (*User, error) {
  784. user := new(User)
  785. has, err := x.SQL("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyID).Get(user)
  786. if err != nil {
  787. return nil, err
  788. } else if !has {
  789. return nil, errors.UserNotKeyOwner{keyID}
  790. }
  791. return user, nil
  792. }
  793. func getUserByID(e Engine, id int64) (*User, error) {
  794. u := new(User)
  795. has, err := e.ID(id).Get(u)
  796. if err != nil {
  797. return nil, err
  798. } else if !has {
  799. return nil, errors.UserNotExist{id, ""}
  800. }
  801. return u, nil
  802. }
  803. // GetUserByID returns the user object by given ID if exists.
  804. func GetUserByID(id int64) (*User, error) {
  805. return getUserByID(x, id)
  806. }
  807. // GetAssigneeByID returns the user with write access of repository by given ID.
  808. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  809. has, err := HasAccess(userID, repo, ACCESS_MODE_READ)
  810. if err != nil {
  811. return nil, err
  812. } else if !has {
  813. return nil, errors.UserNotExist{userID, ""}
  814. }
  815. return GetUserByID(userID)
  816. }
  817. // GetUserByName returns a user by given name.
  818. func GetUserByName(name string) (*User, error) {
  819. if len(name) == 0 {
  820. return nil, errors.UserNotExist{0, name}
  821. }
  822. u := &User{LowerName: strings.ToLower(name)}
  823. has, err := x.Get(u)
  824. if err != nil {
  825. return nil, err
  826. } else if !has {
  827. return nil, errors.UserNotExist{0, name}
  828. }
  829. return u, nil
  830. }
  831. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  832. func GetUserEmailsByNames(names []string) []string {
  833. mails := make([]string, 0, len(names))
  834. for _, name := range names {
  835. u, err := GetUserByName(name)
  836. if err != nil {
  837. continue
  838. }
  839. if u.IsMailable() {
  840. mails = append(mails, u.Email)
  841. }
  842. }
  843. return mails
  844. }
  845. // GetUserIDsByNames returns a slice of ids corresponds to names.
  846. func GetUserIDsByNames(names []string) []int64 {
  847. ids := make([]int64, 0, len(names))
  848. for _, name := range names {
  849. u, err := GetUserByName(name)
  850. if err != nil {
  851. continue
  852. }
  853. ids = append(ids, u.ID)
  854. }
  855. return ids
  856. }
  857. // UserCommit represents a commit with validation of user.
  858. type UserCommit struct {
  859. User *User
  860. *git.Commit
  861. }
  862. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  863. func ValidateCommitWithEmail(c *git.Commit) *User {
  864. u, err := GetUserByEmail(c.Author.Email)
  865. if err != nil {
  866. return nil
  867. }
  868. return u
  869. }
  870. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  871. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  872. var (
  873. u *User
  874. emails = map[string]*User{}
  875. newCommits = list.New()
  876. e = oldCommits.Front()
  877. )
  878. for e != nil {
  879. c := e.Value.(*git.Commit)
  880. if v, ok := emails[c.Author.Email]; !ok {
  881. u, _ = GetUserByEmail(c.Author.Email)
  882. emails[c.Author.Email] = u
  883. } else {
  884. u = v
  885. }
  886. newCommits.PushBack(UserCommit{
  887. User: u,
  888. Commit: c,
  889. })
  890. e = e.Next()
  891. }
  892. return newCommits
  893. }
  894. // GetUserByEmail returns the user object by given e-mail if exists.
  895. func GetUserByEmail(email string) (*User, error) {
  896. if len(email) == 0 {
  897. return nil, errors.UserNotExist{0, "email"}
  898. }
  899. email = strings.ToLower(email)
  900. // First try to find the user by primary email
  901. user := &User{Email: email}
  902. has, err := x.Get(user)
  903. if err != nil {
  904. return nil, err
  905. }
  906. if has {
  907. return user, nil
  908. }
  909. // Otherwise, check in alternative list for activated email addresses
  910. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  911. has, err = x.Get(emailAddress)
  912. if err != nil {
  913. return nil, err
  914. }
  915. if has {
  916. return GetUserByID(emailAddress.UID)
  917. }
  918. return nil, errors.UserNotExist{0, email}
  919. }
  920. type SearchUserOptions struct {
  921. Keyword string
  922. Type UserType
  923. OrderBy string
  924. Page int
  925. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  926. }
  927. // SearchUserByName takes keyword and part of user name to search,
  928. // it returns results in given range and number of total results.
  929. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  930. if len(opts.Keyword) == 0 {
  931. return users, 0, nil
  932. }
  933. opts.Keyword = strings.ToLower(opts.Keyword)
  934. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  935. opts.PageSize = setting.UI.ExplorePagingNum
  936. }
  937. if opts.Page <= 0 {
  938. opts.Page = 1
  939. }
  940. searchQuery := "%" + opts.Keyword + "%"
  941. users = make([]*User, 0, opts.PageSize)
  942. // Append conditions
  943. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  944. Or("LOWER(full_name) LIKE ?", searchQuery).
  945. And("type = ?", opts.Type)
  946. var countSess xorm.Session
  947. countSess = *sess
  948. count, err := countSess.Count(new(User))
  949. if err != nil {
  950. return nil, 0, fmt.Errorf("Count: %v", err)
  951. }
  952. if len(opts.OrderBy) > 0 {
  953. sess.OrderBy(opts.OrderBy)
  954. }
  955. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  956. }
  957. // Follow represents relations of user and his/her followers.
  958. type Follow struct {
  959. ID int64
  960. UserID int64 `xorm:"UNIQUE(follow)"`
  961. FollowID int64 `xorm:"UNIQUE(follow)"`
  962. }
  963. func IsFollowing(userID, followID int64) bool {
  964. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  965. return has
  966. }
  967. // FollowUser marks someone be another's follower.
  968. func FollowUser(userID, followID int64) (err error) {
  969. if userID == followID || IsFollowing(userID, followID) {
  970. return nil
  971. }
  972. sess := x.NewSession()
  973. defer sess.Close()
  974. if err = sess.Begin(); err != nil {
  975. return err
  976. }
  977. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  978. return err
  979. }
  980. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  981. return err
  982. }
  983. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  984. return err
  985. }
  986. return sess.Commit()
  987. }
  988. // UnfollowUser unmarks someone be another's follower.
  989. func UnfollowUser(userID, followID int64) (err error) {
  990. if userID == followID || !IsFollowing(userID, followID) {
  991. return nil
  992. }
  993. sess := x.NewSession()
  994. defer sess.Close()
  995. if err = sess.Begin(); err != nil {
  996. return err
  997. }
  998. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  999. return err
  1000. }
  1001. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1002. return err
  1003. }
  1004. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1005. return err
  1006. }
  1007. return sess.Commit()
  1008. }