Example #1
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 #2
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 #3
0
// AuthRequired run function when user logged in.
func AuthRequired(f func(c *gin.Context)) gin.HandlerFunc {
	return func(c *gin.Context) {
		_, err := userService.CurrentUser(c)
		if err != nil {
			log.Error("Auth failed.")
			response.KnownErrorJSON(c, http.StatusUnauthorized, "error.loginPlease", errors.New("Auth failed."))
			return
		}
		f(c)
		return
	}
}
Example #4
0
// AdminRequired run function when user logged in and user has an admin role.
func AdminRequired(f func(c *gin.Context)) gin.HandlerFunc {
	return func(c *gin.Context) {
		user, err := userService.CurrentUser(c)
		if err == nil {
			if HasAdmin(&user) {
				f(c)
				log.Debug("User has admin role.")
				return
			}
		}
		log.Error("Admin role required.")
		response.KnownErrorJSON(c, http.StatusUnauthorized, "error.adminRequired", errors.New("Admin role required."))
		return
	}
}
Example #5
0
// UpdateUser updates a user.
func UpdateUser(c *gin.Context) (*model.User, int, error) {
	id := c.Params.ByName("id")
	var user model.User
	if db.ORM.First(&user, id).RecordNotFound() {
		return &user, http.StatusNotFound, errors.New("User is not found.")
	}
	switch c.Request.FormValue("type") {
	case "password":
		var passwordForm PasswordForm
		c.BindWith(&passwordForm, binding.Form)
		log.Debugf("form %+v\n", passwordForm)
		err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(passwordForm.CurrentPassword))
		if err != nil {
			log.Error("Password Incorrect.")
			return &user, http.StatusInternalServerError, errors.New("User is not updated. Password Incorrect.")
		} else {
			newPassword, err := bcrypt.GenerateFromPassword([]byte(passwordForm.Password), 10)
			if err != nil {
				return &user, http.StatusInternalServerError, errors.New("User is not updated. Password not Generated.")
			} else {
				passwordForm.Password = string(newPassword)
				modelHelper.AssignValue(&user, &passwordForm)
			}
		}
	default:
		var form UserForm
		c.BindWith(&form, binding.Form)
		log.Debugf("form %+v\n", form)
		modelHelper.AssignValue(&user, &form)
	}

	log.Debugf("params %+v\n", c.Params)
	status, err := UpdateUserCore(&user)
	if err != nil {
		return &user, status, err
	}
	status, err = SetCookie(c, user.Token)
	return &user, status, err
}
Example #6
0
// articleUploader is a uploader that uploading files and sync articles.
func articleUploader() concurrency.ConcurrencyManager {
	return func(reader *multipart.Reader) concurrency.Result {
		atomic.AddInt32(concurrency.BusyWorker, 1)
		var articles []model.Article
		formDataBuffer := make([]byte, 100000)
		fileCount := 0
		sqlStrBuffer := new(bytes.Buffer)
		stringHelper.Concat(sqlStrBuffer, "INSERT INTO article(user_id, title, url, content, image_name, created_at) VALUES ")
		values := []interface{}{}
		var result concurrency.Result
		result.Code = http.StatusOK
		for {
			part, err := reader.NextPart()
			if err == io.EOF {
				break
			}
			if part.FileName() == "" {
				if part.FormName() != "" {
					log.Debug("formName : " + part.FormName())
					n, err := part.Read(formDataBuffer)
					if err != nil {
						log.Warnf("Multipart read failed. , (Error Detail : %s)", err.Error())
						result.Code = http.StatusBadRequest
						result.Error = err
						return result
					}
					log.Debugf("data : %s ", formDataBuffer)
					err = json.Unmarshal(formDataBuffer[:n], &articles)
					if err != nil {
						log.Warnf("Json unmarshal failed. , (Error Detail : %s)", err.Error())
						result.Code = http.StatusBadRequest
						result.Error = err
						return result
					}
					log.Debugf("err %s", err)
					log.Debugf("article : %v\n", articles)
					log.Debugf("article len : %d\n", len(articles))
				}
				continue
			}
			err = upload.UploadImageFile("", part)
			if err != nil {
				log.Error("Image uploading failed. : " + err.Error())
				result.Code = http.StatusBadRequest
				result.Error = err
				return result
			}
			if fileCount < len(articles) {
				stringHelper.Concat(sqlStrBuffer, "(?, ?, ?, ?, ?, ?),")
				values = append(values, user.Id, articles[fileCount].Title, articles[fileCount].Url, articles[fileCount].Content, articles[fileCount].ImageName, time.Now())
				// db.ORM.Create(&articles[fileCount])
				fileCount += 1
			}
			log.Debug("File uploaded.")
			log.Infof("File Count : %d\n", fileCount)
		}
		sqlStr := sqlStrBuffer.String()
		sqlStr = sqlStr[0 : len(sqlStr)-1]
		log.Debugf("sqlStr for Article : %s", sqlStr)
		db.ORM.Exec(sqlStr, values...)
		return result
	}
}