user.go 31 KB

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