Example #1
0
// ResetPassword resets a password of user.
func ResetPassword(c *gin.Context) (int, error) {
	var user model.User
	var passwordResetForm PasswordResetForm
	c.BindWith(&passwordResetForm, binding.Form)
	if db.ORM.Where(&model.User{PasswordResetToken: passwordResetForm.PasswordResetToken}).First(&user).RecordNotFound() {
		return http.StatusNotFound, errors.New("User is not found.")
	}
	isExpired := timeHelper.IsExpired(user.PasswordResetUntil)
	log.Debugf("passwordResetUntil : %s", user.PasswordResetUntil.UTC())
	log.Debugf("expired : %t", isExpired)
	if isExpired {
		return http.StatusForbidden, errors.New("token not valid.")
	}
	newPassword, err := bcrypt.GenerateFromPassword([]byte(passwordResetForm.Password), 10)
	if err != nil {
		return http.StatusInternalServerError, errors.New("User is not updated. Password not Generated.")
	}
	passwordResetForm.Password = string(newPassword)
	log.Debugf("user password before : %s ", user.Password)
	modelHelper.AssignValue(&user, &passwordResetForm)
	user.PasswordResetToken = ""
	user.PasswordResetUntil = time.Now()
	log.Debugf("user password after : %s ", user.Password)
	status, err := UpdateUserCore(&user)
	if err != nil {
		return status, err
	}
	status, err = SetCookie(c, user.Token)
	return status, err
}
Example #2
0
File: file.go Project: tka/goyangi
// CreateFiles creates files.
func CreateFiles(c *gin.Context) (int, error) {
	var forms FilesForm
	start := time.Now()
	c.BindWith(&forms, binding.JSON)
	log.Debugf("CreateFiles c form : %v", forms)

	user, _ := userService.CurrentUser(c)
	sqlStrBuffer := new(bytes.Buffer)
	stringHelper.Concat(sqlStrBuffer, "INSERT INTO file(user_id, name, size, created_at) VALUES ")
	values := []interface{}{}
	for _, file := range forms.Files {
		stringHelper.Concat(sqlStrBuffer, "(?, ?, ?, ?),")
		values = append(values, user.Id, file.Name, file.Size, time.Now())

	}
	// sqlStrBuffer.Truncate(sqlStrBuffer.Len() - 1) is slower than slice.
	if len(values) > 0 {
		sqlStr := sqlStrBuffer.String()
		sqlStr = sqlStr[0 : len(sqlStr)-1]
		log.Debugf("sqlStr for File : %s", sqlStr)
		db.ORM.Exec(sqlStr, values...)
		elapsed := time.Since(start)
		log.Debugf("CreateFiles elapsed : %s", elapsed)
	}

	return http.StatusCreated, nil
}
Example #3
0
// SendPasswordResetToken sends a password reset token.
func SendPasswordResetToken(c *gin.Context) (int, error) {
	var user model.User
	var sendPasswordResetForm SendPasswordResetForm
	var err error
	log.Debugf("c.Params : %v", c.Params)
	c.BindWith(&sendPasswordResetForm, binding.Form)
	if db.ORM.Where(&model.User{Email: sendPasswordResetForm.Email}).First(&user).RecordNotFound() {
		return http.StatusNotFound, errors.New("User is not found. Please Check the email.")
	}
	user.PasswordResetUntil = timeHelper.TwentyFourHoursLater()
	user.PasswordResetToken, err = crypto.GenerateRandomToken16()
	if err != nil {
		return http.StatusInternalServerError, err
	}
	log.Debugf("generated token : %s", user.PasswordResetToken)
	status, err := UpdateUserCore(&user)
	if err != nil {
		return status, err
	}
	err = SendEmailPasswordResetToken(user.Email, user.PasswordResetToken, "en-us")
	if err != nil {
		return http.StatusInternalServerError, err
	}
	return http.StatusOK, nil
}
Example #4
0
// RetrieveLocations retrieves locations.
func RetrieveLocations(c *gin.Context) ([]model.Location, bool, int, bool, bool, int, error) {
	var locations []model.Location
	var locationCount, locationPerPage int
	filterQuery := c.Request.URL.Query().Get("filter")
	locationPerPage = config.LocationPerPage
	filter := &LocationFilter{}
	whereBuffer := new(bytes.Buffer)
	whereValues := []interface{}{}
	if len(filterQuery) > 0 {
		log.Debugf("retrieve Locations filter : %s\n", filterQuery)
		json.Unmarshal([]byte(filterQuery), &filter)
		if filter.UserId > 0 {
			stringHelper.Concat(whereBuffer, "user_id = ?")
			whereValues = append(whereValues, filter.UserId)
			log.Debugf("userId : %d\n", filter.UserId)
		}
		if filter.LocationPerPage > 0 {
			locationPerPage = filter.LocationPerPage
			log.Debugf("locationPerPage : %d\n", filter.LocationPerPage)
		}
	} else {
		log.Debug("no filters found.\n")
	}
	log.Debugf("filterQuery %v.\n", filterQuery)
	log.Debugf("filter %v.\n", filter)
	whereStr := whereBuffer.String()
	db.ORM.Model(model.Location{}).Where(whereStr, whereValues...).Count(&locationCount)
	offset, currentPage, hasPrev, hasNext := pagination.Paginate(filter.CurrentPage, locationPerPage, locationCount)
	db.ORM.Limit(locationPerPage).Offset(offset).Order(config.LocationOrder).Where(whereStr, whereValues...).Find(&locations)

	return locations, canUserWrite(c), currentPage, hasPrev, hasNext, http.StatusOK, nil
}
Example #5
0
// LoginOrCreateOauthUser login or create with oauthUser
func LoginOrCreateOauthUser(c *gin.Context, oauthUser *OauthUser, providerID int64, token *oauth2.Token) (int, error) {
	var connection model.Connection
	var count int
	db.ORM.Where("provider_id = ? and provider_user_id = ?", providerID, oauthUser.Id).First(&connection).Count(&count)

	connection.ProviderId = providerID
	connection.ProviderUserId = oauthUser.Id
	connection.AccessToken = token.AccessToken
	connection.ProfileUrl = oauthUser.ProfileUrl
	connection.ImageUrl = oauthUser.ImageUrl
	log.Debugf("connection count : %v", count)
	if count == 1 {
		var user model.User
		if db.ORM.First(&user, "id = ?", connection.UserId).RecordNotFound() {
			return http.StatusNotFound, errors.New("User is not found.")
		}
		log.Debugf("user : %v", user)
		if db.ORM.Save(&connection).Error != nil {
			return http.StatusInternalServerError, errors.New("Connection is not updated.")
		}
		status, err := LoginWithOauthUser(c, user.Token)
		return status, err
	}
	log.Debugf("Connection is not exist.")
	user, status, err := CreateOauthUser(c, oauthUser, &connection)
	if err != nil {
		return status, err
	}
	status, err = LoginWithOauthUser(c, user.Token)
	return status, err
}
Example #6
0
// OauthGithub link connection and user.
func OauthGithub(c *gin.Context) (int, error) {
	var authResponse oauth2.AuthResponse
	var oauthUser OauthUser
	c.BindWith(&authResponse, binding.Form)
	log.Debugf("oauthRedirect form: %v", authResponse)
	response, token, err := oauth2.OauthRequest(github.RequestURL, github.Config, authResponse)
	if err != nil {
		log.Error("get response error")
		return http.StatusInternalServerError, err
	}
	githubUser, err := SetGithubUser(response)
	if err != nil {
		log.Error("SetGithubUser error")
		return http.StatusInternalServerError, err
	}
	modelHelper.AssignValue(&oauthUser, githubUser)
	oauthUser.Id = strconv.Itoa(githubUser.UserId)
	log.Debugf("\noauthUser item : %v", oauthUser)
	status, err := LoginOrCreateOauthUser(c, &oauthUser, github.ProviderId, token)
	if err != nil {
		log.Errorf("LoginOrCreateOauthUser error: %d", status)
		return status, err
	}
	return http.StatusSeeOther, nil
}
Example #7
0
// RetrieveArticle retrieve an article.
func RetrieveArticle(c *gin.Context) (model.Article, bool, int64, int, error) {
	var article model.Article
	var count int
	var currentUserId int64
	var isAuthor bool
	id := c.Params.ByName("id")
	if db.ORM.First(&article, "id = ?", id).RecordNotFound() {
		return article, isAuthor, currentUserId, http.StatusNotFound, errors.New("Article is not found.")
	}
	log.Debugf("Article : %s\n", article)
	log.Debugf("Count : %s\n", count)
	currentUser, err := userService.CurrentUser(c)
	if err == nil {
		currentUserId = currentUser.Id
		isAuthor = currentUser.Id == article.UserId
	}

	assignRelatedUser(&article)
	var commentList model.CommentList
	comments, currentPage, hasPrev, hasNext, _ := commentService.RetrieveComments(article)
	commentList.Comments = comments
	commentService.SetCommentPageMeta(&commentList, currentPage, hasPrev, hasNext, article.CommentCount)
	article.CommentList = commentList
	var likingList model.LikingList
	likings, currentPage, hasPrev, hasNext, _ := likingRetriever.RetrieveLikings(article)
	likingList.Likings = likings
	currentUserlikedCount := db.ORM.Model(&article).Where("id =?", currentUserId).Association("Likings").Count()
	log.Debugf("Current user like count : %d", currentUserlikedCount)
	likingMeta.SetLikingPageMeta(&likingList, currentPage, hasPrev, hasNext, article.LikingCount, currentUserlikedCount)
	article.LikingList = likingList
	return article, isAuthor, currentUserId, http.StatusOK, nil
}
Example #8
0
// RetrieveOauthStatus retrieves ouath status that provider connected or not.
func RetrieveOauthStatus(c *gin.Context) (oauthStatusMap, int, error) {
	var oauthStatus oauthStatusMap
	var connections []model.Connection
	oauthStatus = make(oauthStatusMap)
	currentUser, err := userService.CurrentUser(c)
	if err != nil {
		return oauthStatus, http.StatusUnauthorized, err
	}
	db.ORM.Model(&currentUser).Association("Connections").Find(&connections)
	for _, connection := range connections {
		log.Debugf("connection.ProviderId : %d", connection.ProviderId)
		switch connection.ProviderId {
		case google.ProviderId:
			oauthStatus["google"] = true
		case github.ProviderId:
			oauthStatus["github"] = true
		case yahoo.ProviderId:
			oauthStatus["yahoo"] = true
		case facebook.ProviderId:
			oauthStatus["facebook"] = true
		case twitter.ProviderId:
			oauthStatus["twitter"] = true
		case linkedin.ProviderId:
			oauthStatus["linkedin"] = true
		case kakao.ProviderId:
			oauthStatus["kakao"] = true
		case naver.ProviderId:
			oauthStatus["naver"] = true
		}
	}
	log.Debugf("oauthStatus : %v", oauthStatus)
	return oauthStatus, http.StatusOK, nil
}
Example #9
0
// EmailVerification verifies an email of user.
func EmailVerification(c *gin.Context) (int, error) {
	var user model.User
	var verifyEmailForm VerifyEmailForm
	c.BindWith(&verifyEmailForm, binding.Form)
	log.Debugf("verifyEmailForm.ActivationToken : %s", verifyEmailForm.ActivationToken)
	if db.ORM.Where(&model.User{ActivationToken: verifyEmailForm.ActivationToken}).First(&user).RecordNotFound() {
		return http.StatusNotFound, errors.New("User is not found.")
	}
	isExpired := timeHelper.IsExpired(user.ActivateUntil)
	log.Debugf("passwordResetUntil : %s", user.ActivateUntil.UTC())
	log.Debugf("expired : %t", isExpired)
	if isExpired {
		return http.StatusForbidden, errors.New("token not valid.")
	}
	user.ActivationToken = ""
	user.ActivateUntil = time.Now()
	user.ActivatedAt = time.Now()
	user.Activation = true
	status, err := UpdateUserCore(&user)
	if err != nil {
		return status, err
	}
	status, err = SetCookie(c, user.Token)
	return status, err
}
Example #10
0
func FewDurationLater(duration time.Duration) time.Time {
	// When Save time should considering UTC
	baseTime := time.Now()
	log.Debugf("basetime : %s", baseTime)
	fewDurationLater := baseTime.Add(duration)
	log.Debugf("time : %s", fewDurationLater)
	return fewDurationLater
}
Example #11
0
// RegisterHanderFromForm sets cookie from a RegistrationForm.
func RegisterHanderFromForm(c *gin.Context, registrationForm RegistrationForm) (int, error) {
	email := registrationForm.Email
	pass := registrationForm.Password
	log.Debugf("RegisterHandler UserEmail : %s", email)
	log.Debugf("RegisterHandler UserPassword : %s", pass)
	status, err := SetCookieHandler(c, email, pass)
	return status, err
}
Example #12
0
func IsExpired(expirationTime time.Time) bool {
	baseTime := time.Now()
	log.Debugf("basetime : %s", baseTime)
	log.Debugf("expirationTime : %s", expirationTime)
	elapsed := time.Since(expirationTime)
	log.Debugf("elapsed : %s", elapsed)
	after := time.Now().After(expirationTime)
	log.Debugf("after : %t", after)
	return after
}
Example #13
0
// SetNaverUser set naver user.
func SetNaverUser(response *http.Response) (*NaverUser, error) {
	naverUser := &NaverUser{}
	defer response.Body.Close()
	log.Debugf("response.Body: %v\n", response.Body)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return naverUser, err
	}
	json.Unmarshal(body, &naverUser)
	log.Debugf("\nnaverUser: %v\n", naverUser)
	return naverUser, err
}
Example #14
0
// SetKakaoUser set kakao user.
func SetKakaoUser(response *http.Response) (*KakaoUser, error) {
	kakaoUser := &KakaoUser{}
	defer response.Body.Close()

	log.Debugf("response.Body: %v\n", response.Body)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return kakaoUser, err
	}
	json.Unmarshal(body, &kakaoUser)
	log.Debugf("\nkakaoUser: %v\n", kakaoUser)
	return kakaoUser, err
}
Example #15
0
// imageUploader is a uploader that uploading files.
func imageUploader() concurrency.ConcurrencyManager {
	return func(reader *multipart.Reader) concurrency.Result {
		atomic.AddInt32(concurrency.BusyWorker, 1)
		var result concurrency.Result
		result.Code = http.StatusOK
		for {
			part, err := reader.NextPart()

			uploadedNow := atomic.AddUint32(concurrency.Done, 1)
			log.Debugf("count %d", uploadedNow)
			if err == io.EOF {
				log.Debug("End of file.")
				break
			}
			if part.FileName() == "" {
				log.Debug("File name is empty.")
				continue
			}
			err = upload.UploadImageFile(s3UploadPath, part)
			if err != nil {
				log.Error("Image uploading failed. : " + err.Error())
				result.Code = http.StatusBadRequest
				result.Error = err
				return result
			}
			log.Debug("File uploaded.")
		}
		log.Debug("Iteration concurrency.Done.")
		return result
	}
}
Example #16
0
// RetrieveLikingsOnArticles retrieves likings on article.
func RetrieveLikingsOnArticles(c *gin.Context) ([]model.User, int, bool, bool, int, int, error) {
	var article model.Article
	var likings []model.User
	var retrieveListForm form.RetrieveListForm
	var hasPrev, hasNext bool
	var currentPage, count int
	articleId := c.Params.ByName("id")
	log.Debugf("Liking params : %v", c.Params)
	c.BindWith(&retrieveListForm, binding.Form)
	log.Debugf("retrieveListForm %+v\n", retrieveListForm)
	if db.ORM.First(&article, articleId).RecordNotFound() {
		return likings, currentPage, hasPrev, hasNext, count, http.StatusNotFound, errors.New("Article is not found.")
	}
	likings, currentPage, hasPrev, hasNext, count = likingRetriever.RetrieveLikings(article, retrieveListForm.CurrentPage)
	return likings, currentPage, hasPrev, hasNext, count, http.StatusOK, nil
}
Example #17
0
// RetrieveLikingsOnLocations retrieves likings on location.
func RetrieveLikingsOnLocations(c *gin.Context) ([]*model.PublicUser, int, bool, bool, int, int, error) {
	var location model.Location
	var likings []*model.PublicUser
	var retrieveListForm form.RetrieveListForm
	var hasPrev, hasNext bool
	var currentPage, count int
	locationId := c.Params.ByName("id")
	log.Debugf("Liking params : %v", c.Params)
	c.BindWith(&retrieveListForm, binding.Form)
	log.Debugf("retrieveListForm %+v\n", retrieveListForm)
	if db.ORM.First(&location, locationId).RecordNotFound() {
		return likings, currentPage, hasPrev, hasNext, count, http.StatusNotFound, errors.New("Location is not found.")
	}
	likings, currentPage, hasPrev, hasNext, count = likingRetriever.RetrieveLikings(location, retrieveListForm.CurrentPage)
	return likings, currentPage, hasPrev, hasNext, count, http.StatusOK, nil
}
Example #18
0
// RetrieveUser retrieves a user.
func RetrieveUser(c *gin.Context) (*model.PublicUser, bool, int64, int, error) {
	var user model.User
	var currentUserId int64
	var isAuthor bool
	// var publicUser *model.PublicUser
	// publicUser.User = &user
	id := c.Params.ByName("id")
	if db.ORM.Select(config.UserPublicFields).First(&user, id).RecordNotFound() {
		return &model.PublicUser{User: &user}, isAuthor, currentUserId, http.StatusNotFound, errors.New("User is not found.")
	}
	currentUser, err := CurrentUser(c)
	if err == nil {
		currentUserId = currentUser.Id
		isAuthor = currentUser.Id == user.Id
	}
	var likingList model.LikingList
	likings, currentPage, hasPrev, hasNext, _ := likingRetriever.RetrieveLikings(user)
	likingList.Likings = likings
	currentUserlikedCount := db.ORM.Model(&user).Where("id =?", currentUserId).Association("Likings").Count()
	log.Debugf("Current user like count : %d", currentUserlikedCount)
	likingMeta.SetLikingPageMeta(&likingList, currentPage, hasPrev, hasNext, user.LikingCount, currentUserlikedCount)
	user.LikingList = likingList
	var likedList model.LikedList
	liked, currentPage, hasPrev, hasNext, _ := likingRetriever.RetrieveLiked(user)
	likedList.Liked = liked
	likingMeta.SetLikedPageMeta(&likedList, currentPage, hasPrev, hasNext, user.LikedCount)
	user.LikedList = likedList
	return &model.PublicUser{User: &user}, isAuthor, currentUserId, http.StatusOK, nil
}
Example #19
0
// Upload uploads file to a storage.
func Upload(reader *multipart.Reader, kind int) {
	c := make(chan UploadStatus)
	switch kind {
	case KindUploaderBasic:
		go func() {
			c <- UploadAgent(reader, 업로더, BasicUploader, Cargador, Shàngchuán, загрузчик)
		}()
	case KindUploaderArticle:
		go func() {
			c <- UploadAgent(reader, Article업로더, ArticleUploader, ArticleCargador, ArticleShàngchuán, Articleзагрузчик)
		}()
	default:
		go func() {
			c <- UploadAgent(reader, 업로더, BasicUploader, Cargador, Shàngchuán, загрузчик)
		}()
	}

	timeout := time.After(config.UploadTimeout)
	select {
	case <-c:
		workingNow := atomic.AddInt32(workingUploader, -1)
		log.Debugf("All files are uploaded. Working uploader count : %d", workingNow)
		return
	case <-timeout:
		fmt.Println("timed out")
		return
	}
}
Example #20
0
File: file.go Project: tka/goyangi
// DeleteFile deletes a file.
func DeleteFile(c *gin.Context) (int, error) {
	log.Debug("deleteFile performed")
	var targetFile model.File
	id := c.Params.ByName("id")
	if db.ORM.First(&targetFile, id).RecordNotFound() {
		return http.StatusNotFound, errors.New("File is not found.")
	}
	status, err := userPermission.CurrentUserIdentical(c, targetFile.UserId)
	if err != nil {
		return status, err
	}
	switch config.UploadTarget {
	case "S3":
		s3UploadPath := config.UploadS3Path + strconv.FormatInt(targetFile.UserId, 10) + "/"
		log.Debugf("s3UploadPath %s", s3UploadPath)
		err = aws.DelFromMyBucket(s3UploadPath, targetFile.Name)
		if err != nil {
			return http.StatusInternalServerError, err
		}
	case "LOCAL":
		err = file.DeleteLocal(targetFile.Name)
		if err != nil {
			return http.StatusInternalServerError, err
		}
	}

	if db.ORM.Delete(&targetFile).Delete(targetFile).Error != nil {
		return http.StatusInternalServerError, errors.New("File is not deleted.")
	}
	return http.StatusOK, nil
}
Example #21
0
// RetrieveLocation retrieves a location.
func RetrieveLocation(c *gin.Context) (model.Location, bool, int64, int, error) {
	var location model.Location
	var currentUserId int64
	isAuthor := false
	id := c.Params.ByName("id")
	if db.ORM.First(&location, "id = ?", id).RecordNotFound() {
		return location, isAuthor, currentUserId, http.StatusNotFound, errors.New("Location is not found.")
	}
	currentUser, err := userService.CurrentUser(c)
	if err == nil {
		currentUserId = currentUser.Id
		isAuthor = currentUser.Id == location.UserId
	}
	assignRelatedUser(&location)
	var commentList model.CommentList
	comments, currentPage, hasPrev, hasNext, _ := commentService.RetrieveComments(location)
	commentList.Comments = comments
	commentService.SetCommentPageMeta(&commentList, currentPage, hasPrev, hasNext, location.CommentCount)
	location.CommentList = commentList
	var likingList model.LikingList
	likings, currentPage, hasPrev, hasNext, _ := likingRetriever.RetrieveLikings(location)
	likingList.Likings = likings
	currentUserlikedCount := db.ORM.Model(&location).Where("id =?", currentUserId).Association("Likings").Count()
	log.Debugf("Current user like count : %d", currentUserlikedCount)
	likingMeta.SetLikingPageMeta(&likingList, currentPage, hasPrev, hasNext, location.LikingCount, currentUserlikedCount)
	location.LikingList = likingList
	return location, isAuthor, currentUserId, http.StatusOK, nil
}
Example #22
0
// SetCookieHandler sets a cookie with email and password.
func SetCookieHandler(c *gin.Context, email string, pass string) (int, error) {
	if email != "" && pass != "" {
		log.Debugf("User email : %s , password : %s", email, pass)
		var user model.User
		isValidEmail := validation.EmailValidation(email)
		if isValidEmail {
			log.Debug("User entered valid email.")
			if db.ORM.Where("email = ?", email).First(&user).RecordNotFound() {
				return http.StatusNotFound, errors.New("User is not found.")
			}
		} else {
			log.Debug("User entered username.")
			if db.ORM.Where("username = ?", email).First(&user).RecordNotFound() {
				return http.StatusNotFound, errors.New("User is not found.")
			}
		}
		err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(pass))
		if err != nil {
			return http.StatusUnauthorized, errors.New("Password incorrect.")
		}
		status, err := SetCookie(c, user.Token)
		if err != nil {
			return status, err
		}
		c.Writer.Header().Set("X-Auth-Token", user.Token)
		return http.StatusOK, nil
	} else {
		return http.StatusNotFound, errors.New("User is not found.")
	}
}
Example #23
0
// Your credentials should be obtained from the Google
// Developer Console (https://console.developers.google.com).
func OauthURL(conf *oauth2.Config) string {
	// Redirect user to Google's consent page to ask for permission
	// for the scopes specified above.

	url := conf.AuthCodeURL("state")
	log.Debugf("\nVisit the URL for the auth dialog: %v\n", url)
	return url
}
Example #24
0
// CreateUserFromForm creates a user from a registration form.
func CreateUserFromForm(registrationForm RegistrationForm) (model.User, error) {
	var user model.User
	log.Debugf("registrationForm %+v\n", registrationForm)
	modelHelper.AssignValue(&user, &registrationForm)
	user.Md5 = crypto.GenerateMD5Hash(user.Email)
	token, err := crypto.GenerateRandomToken32()
	if err != nil {
		return user, errors.New("Token not generated.")
	}
	user.Token = token
	user.TokenExpiration = timeHelper.FewDaysLater(config.AuthTokenExpirationDay)
	log.Debugf("user %+v\n", user)
	if db.ORM.Create(&user).Error != nil {
		return user, errors.New("User is not created.")
	}
	return user, nil
}
Example #25
0
// RetrieveArticles retrieves articles.
func RetrieveArticles(c *gin.Context) ([]model.Article, bool, int, int, bool, bool, int, error) {
	var articles []model.Article
	var category int
	var articleCount, articlePerPage int
	filterQuery := c.Request.URL.Query().Get("filter")
	articlePerPage = config.ArticlePerPage
	filter := &ArticleFilter{}
	whereBuffer := new(bytes.Buffer)
	whereValues := []interface{}{}
	if len(filterQuery) > 0 {
		log.Debugf("retrieve Articles filter : %s\n", filterQuery)
		json.Unmarshal([]byte(filterQuery), &filter)
		if filter.UserId > 0 {
			stringHelper.Concat(whereBuffer, "user_id = ?")
			whereValues = append(whereValues, filter.UserId)
			log.Debugf("userId : %d\n", filter.UserId)
		}
		if len(filter.Categories) > 0 {
			if len(whereValues) == 1 {
				stringHelper.Concat(whereBuffer, " and ")
			}
			stringHelper.Concat(whereBuffer, "category_id = ?")
			whereValues = append(whereValues, filter.Categories[0])
			log.Debugf("categories : %d\n", filter.Categories[0])
			category = filter.Categories[0]
		}
		if filter.ArticlePerPage > 0 {
			articlePerPage = filter.ArticlePerPage
			log.Debugf("articlePerPage : %d\n", filter.ArticlePerPage)
		}
	} else {
		log.Debug("no filters found.\n")
	}
	log.Debugf("filterQuery %v.\n", filterQuery)
	log.Debugf("filter %v.\n", filter)
	whereStr := whereBuffer.String()
	log.Debugf("whereStr %s.\n", whereStr)
	log.Debugf("whereValues %v.\n", whereValues)
	db.ORM.Model(model.Article{}).Where(whereStr, whereValues...).Count(&articleCount)
	offset, currentPage, hasPrev, hasNext := pagination.Paginate(filter.CurrentPage, articlePerPage, articleCount)
	log.Debugf("currentPage, perPage, total : %d, %d, %d", filter.CurrentPage, articlePerPage, articleCount)
	log.Debugf("offset, currentPage, hasPrev, hasNext : %d, %d, %t, %t", offset, currentPage, hasPrev, hasNext)
	db.ORM.Limit(articlePerPage).Offset(offset).Order(config.ArticleOrder).Where(whereStr, whereValues...).Find(&articles)
	return articles, canUserWrite(c, category), category, currentPage, hasPrev, hasNext, http.StatusOK, nil
}
Example #26
0
func SendEmailFromAdmin(to string, subject string, body string, bodyHTML string) error {
	msg := gomail.NewMessage()
	msg.SetHeader("From", config.EmailFrom)
	msg.SetHeader("To", to, config.EmailTestTo)
	msg.SetHeader("Subject", subject)
	msg.SetBody("text/plain", body)
	msg.AddAlternative("text/html", bodyHTML)
	log.Debugf("to : %s", to)
	log.Debugf("subject : %s", subject)
	log.Debugf("body : %s", body)
	log.Debugf("bodyHTML : %s", bodyHTML)
	if config.SendEmail {
		log.Debug("SendEmail performed.")
		err := SendEmail(msg)
		return err
	}
	return nil
}
Example #27
0
// HasAdmin checks that user has an admin permission.
func HasAdmin(user *model.User) bool {
	name := "admin"
	for _, role := range user.Roles {
		log.Debugf("HasAdmin role.Name : %s", role.Name)
		if role.Name == name {
			return true
		}
	}
	return false
}
Example #28
0
// SetFacebookUser set facebook user.
func SetFacebookUser(response *http.Response) (*FacebookUser, error) {
	facebookUser := &FacebookUser{}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return facebookUser, err
	}
	json.Unmarshal(body, &facebookUser)
	log.Debugf("\nfacebookUser: %v\n", facebookUser)
	return facebookUser, nil
}
Example #29
0
// RemoveRoleFromUser removes a role from a user.
func RemoveRoleFromUser(c *gin.Context) (int, error) {
	var user model.User
	var role model.Role
	log.Debugf("params : %v\n", c.Params)
	userId := c.Params.ByName("id")
	roleId := c.Params.ByName("roleId")
	if db.ORM.First(&user, userId).RecordNotFound() {
		return http.StatusNotFound, errors.New("User is not found.")
	}
	if db.ORM.First(&role, roleId).RecordNotFound() {
		return http.StatusNotFound, errors.New("Role is not found.")
	}

	log.Debugf("user : %v\n", user)
	log.Debugf("role : %v\n", role)
	if db.ORM.Model(&user).Association("Roles").Delete(role).Error != nil {
		return http.StatusInternalServerError, errors.New("Role is not deleted from user.")
	}
	return http.StatusOK, nil
}
Example #30
0
// SetYahooUser set yahoo user.
func SetYahooUser(response *http.Response) (*YahooUser, error) {
	yahooUser := &YahooUser{}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return yahooUser, err
	}
	json.Unmarshal(body, &yahooUser)
	log.Debugf("\nyahooUser: %v\n", yahooUser)
	return yahooUser, err
}