user.go 31 KB

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