Esempio n. 1
0
func gmMockWrapper(resp http.ResponseWriter, req *http.Request, handler http.HandlerFunc) {
	email := req.URL.Query().Get("email")
	if len(email) <= 0 {
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Need email",
		})
		return
	}

	userDb := public.GetNewUserDatabase()
	defer userDb.Session.Close()

	profiles := userDb.C(USER_DB_PROFILE_COLLECTION)
	q := profiles.Find(bson.M{"email": email})
	user := db.User{}
	if e := q.One(&user); e != nil {
		public.LogE.Printf("Get controlled user failed: %s\n", e.Error())
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Need email",
		})
		return
	}

	req.Header.Set(public.GM_PERMITTED_HEADER_KEY, user.Id.Hex())
	handler(resp, req)
}
Esempio n. 2
0
func handleQueryAccount(resp http.ResponseWriter, req *http.Request) {
	email := req.URL.Query().Get("email")
	if len(email) > 0 {
		userDb := public.GetNewUserDatabase()
		defer userDb.Session.Close()

		profiles := userDb.C(USER_DB_PROFILE_COLLECTION)
		q := profiles.Find(bson.M{"email": email})
		user := db.User{}
		if e := q.One(&user); e == nil {
			//GM can get more information
			public.ResponseOkAsJson(resp, &user)
		} else {
			public.ResponseStatusAsJson(resp, 404, nil)
		}
	} else {
		public.ResponseStatusAsJson(resp, 404, nil)
	}
}
Esempio n. 3
0
func handleUserProfile(resp http.ResponseWriter, req *http.Request) {
	userId, _ := public.GetSessionUserId(req)

	userDb := public.GetNewUserDatabase()
	defer userDb.Session.Close()

	profile := userDb.C(USER_DB_PROFILE_COLLECTION)

	q := profile.FindId(userId)
	if c, err := q.Count(); c == 0 || err != nil {
		r := public.SimpleResult{
			Message:     "Error",
			Description: "User Not Found",
		}
		public.ResponseStatusAsJson(resp, 500, &r)
	} else {
		user := db.User{}
		q.One(&user)

		r := public.UserProfile{
			Email:    user.Email,
			Username: user.Username,
			FormalId: user.FormalId,
		}

		if client, err := storage.GetNewStorageClient(); err == nil && len(user.Thumbnail) > 0 {
			defer client.Close()
			expire := time.Now().Add(time.Duration(12) * time.Hour)
			if r.Thumbnail, err = client.GetNewSignedURL(user.Thumbnail, expire); err != nil {
				r.Thumbnail = ""
			}
		}

		public.ResponseOkAsJson(resp, &r)
	}
}
Esempio n. 4
0
func handleSubmitReview(resp http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	appHash := vars["appHash"]

	appId, ok := exportAppHashMap[appHash]
	if !ok {
		public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{
			Message:     "Error",
			Description: "Hash not found",
		})
		return
	}
	delete(exportAppHashMap, appHash)

	userId, _ := public.GetSessionReviewerId(req)

	reviewDb := public.GetNewReviewerDatabase()
	defer reviewDb.Session.Close()
	userDb := public.GetNewUserDatabase()
	defer userDb.Session.Close()

	results := reviewDb.C(REVIEWER_DB_RESULT_COLLECTION)
	profiles := reviewDb.C(REVIEWER_DB_PROFILE_COLLECTION)

	//See if exist
	//Re-submit is not allowed
	q := results.Find(bson.M{
		"applicationid": appId,
		"reviewerid":    userId,
	})
	if n, _ := q.Count(); n > 0 {
		public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{
			Message:     "Error",
			Description: "Data exist",
		})
		return
	}

	//Get user profile info
	q = profiles.FindId(userId)
	user := db.User{}
	if err := q.One(&user); err != nil {
		public.ResponseStatusAsJson(resp, 404, nil)
		return
	}

	//Get review json data
	reviewData := public.ReviewResponse{}
	body, _ := ioutil.ReadAll(req.Body)

	if err := json.Unmarshal(body, &reviewData); err != nil {
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Wrong review response",
		})
		return
	}

	reviewResult := db.ReviewResult{
		ApplicationId: appId,
		ReviewerId:    userId,
	}
	(&reviewResult).CopyFromReviewResponse(reviewData)

	if err := results.Insert(&reviewResult); err != nil {
		public.LogE.Printf("Error inserting new review result: %s\n", err)
	}

	public.ResponseOkAsJson(resp, nil)
}
Esempio n. 5
0
func handleGMLogin(resp http.ResponseWriter, req *http.Request) {
	email := public.EmailFilter(req.FormValue("email"))
	password := req.FormValue("password")

	if len(email) <= 0 || len(password) <= 0 {
		r := public.SimpleResult{
			Message:     "Error",
			Description: "Incorrect email or password",
		}
		public.ResponseStatusAsJson(resp, 403, &r)
		return
	}

	//Check login status
	if _, err := public.GetSessionGMId(req); err == nil {
		r := public.SimpleResult{
			Message:     "Already Login",
			Description: email,
		}
		public.ResponseOkAsJson(resp, &r)
		return
	}

	userDb := public.GetNewUserDatabase()
	defer userDb.Session.Close()

	profiles := userDb.C(USER_DB_PROFILE_COLLECTION)
	q := profiles.Find(bson.M{"email": email})
	user := db.User{}
	if q.One(&user) == nil {
		//Check password
		if bcrypt.CompareHashAndPassword([]byte(user.AuthInfo.BcyptHash), []byte(password)) != nil {
			r := public.SimpleResult{
				Message:     "Error",
				Description: "Incorrect email or password",
			}
			public.ResponseStatusAsJson(resp, 403, &r)
			return
		}

		//Check whether is GM
		admin := userDb.C(USER_DB_GM_COLLECTION)
		admin_q := admin.Find(bson.M{"userid": user.Id})
		if n, _ := admin_q.Count(); n <= 0 {
			//Not GM
			public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{
				Message:     "Error",
				Description: "Not GM, YOU SHALL NOT PASS",
			})
			return
		}

		if err := public.SetGMSessionValue(req, resp, public.GM_ID_SESSION_KEY, user.Id.Hex()); err != nil {
			public.LogE.Printf("Error setting session user id: %s\n", err.Error())
		}
		r := public.SimpleResult{
			Message:     "Login Successed",
			Description: email,
		}
		public.ResponseOkAsJson(resp, &r)
	} else {
		r := public.SimpleResult{
			Message:     "Error",
			Description: "Incorrect email or password",
		}
		public.ResponseStatusAsJson(resp, 403, &r)
		return
	}
}
Esempio n. 6
0
func handleRegister(resp http.ResponseWriter, req *http.Request) {
	email := public.EmailFilter(req.FormValue("email"))
	username := req.FormValue("username")
	formalId := req.FormValue("formalId")
	password := req.FormValue("password")

	//Verify values first
	var errorFields []string
	if len(email) <= 0 {
		errorFields = append(errorFields, "Email")
	}
	if len(username) <= 0 {
		errorFields = append(errorFields, "Username")
	}
	if len(password) <= 0 {
		errorFields = append(errorFields, "Password")
	}
	if len(formalId) != 10 {
		errorFields = append(errorFields, "FormalId")
	} else {
		if match, _ := regexp.MatchString("[A-Z][12][0-9]{8}", formalId); match {
			if !public.FormalIdVerifier(formalId) {
				errorFields = append(errorFields, "FormalId")
			}
		} else {
			errorFields = append(errorFields, "FormalId")
		}
	}

	if len(errorFields) > 0 {
		r := public.SimpleResult{
			Message:     "Error",
			Description: "Wrong Format: " + strings.Join(errorFields, ","),
		}
		public.ResponseStatusAsJson(resp, 400, &r)
	} else {
		//Get thumbnail if exist
		var thumb multipart.File = nil
		var thumbHeader *multipart.FileHeader = nil
		if f, h, err := req.FormFile("thumbnail"); err == nil && f != nil {
			thumb = f
			thumbHeader = h
		}

		userDb := public.GetNewUserDatabase()
		defer userDb.Session.Close()

		profile := userDb.C(USER_DB_PROFILE_COLLECTION)
		q := profile.Find(bson.M{"email": email})
		if cnt, err := q.Count(); cnt != 0 || err != nil {
			if err != nil {
				r := public.SimpleResult{
					Message:     "Error",
					Description: err.Error(),
				}
				public.ResponseStatusAsJson(resp, 500, &r)
			} else {
				//User exist
				r := public.SimpleResult{
					Message:     "Error",
					Description: "User Exists",
				}
				public.ResponseStatusAsJson(resp, 400, &r)
			}
		} else {
			newUser := db.User{
				Email:    email,
				Username: username,
				FormalId: formalId,
			}
			hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
			newUser.AuthInfo = db.UserAuth{
				BcryptCost: bcrypt.DefaultCost,
				BcyptHash:  string(hash),
			}

			//Store thumbnail
			if thumb != nil {
				defer thumb.Close()
				if client, err := storage.GetNewStorageClient(); err == nil {

					h := public.NewHashString()
					objName := storage.PathJoin(storage.THUMBNAILS_FOLDER_NAME, h)
					//Determine the extension
					var ext string = ""
					if thumbHeader != nil {
						if segs := strings.Split(thumbHeader.Filename, "."); len(segs) > 1 {
							ext = "." + segs[len(segs)-1]
							objName = (objName + ext)
						}
					}

					obj := client.GetDefaultBucket().Object(objName)
					if attr, _ := obj.Attrs(client.Ctx); attr != nil {
						if mimeStr := mime.TypeByExtension(ext); len(mimeStr) > 0 {
							attr.ContentType = mimeStr
						}
					}
					objWriter := obj.NewWriter(client.Ctx)
					defer objWriter.Close()

					_, err = io.Copy(objWriter, thumb)
					if err == nil {
						newUser.Thumbnail = objName
					}
				}
			}

			if err := profile.Insert(&newUser); err != nil {
				r := public.SimpleResult{
					Message:     "Register Failed",
					Description: err.Error(),
				}
				public.ResponseStatusAsJson(resp, 400, &r)
			} else {
				if err := public.SetUserSessionValue(req, resp, public.USER_ID_SESSION_KEY, newUser.Id.Hex()); err != nil {
					public.LogE.Printf("Error setting session user id: %s\n", err.Error())
				}

				if err := public.SetUserSessionValue(req, resp, public.USER_PERMISSION_SESSION_KEY, newUser.Permission); err != nil {
					public.LogE.Printf("Error setting session user permission: %s\n", err.Error())
				}

				r := public.SimpleResult{
					Message:     "Register Successed",
					Description: email,
				}
				public.ResponseOkAsJson(resp, &r)
			}
		}
	}
}
Esempio n. 7
0
func handleApplicationStatus(resp http.ResponseWriter, req *http.Request) {
	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()

	appC := appDb.C(public.APPLICATION_DB_FORM_COLLECTION)
	q := appC.Find(bson.M{})

	result := resultAppStatus{
		TotalApplicationNum: 0,
		TopicsNum:           make([]int, len(TOPICS), len(TOPICS)),

		AccountNum:         0,
		AccountNotApplyNum: 0,
	}
	form := db.ApplicationForm{}
	it := q.Iter()
	for it.Next(&form) {
		result.TotalApplicationNum++

		switch uint(form.Topic) {
		case 0:
			result.TopicsNum[0] += 1
			break

		case 1:
			result.TopicsNum[1] += 1
			break

		case 2:
			result.TopicsNum[2] += 1
			break

		case 3:
			result.TopicsNum[3] += 1
			break

		case 4:
			result.TopicsNum[4] += 1
			break
		}
	}

	userDb := public.GetNewUserDatabase()
	defer userDb.Session.Close()

	profileC := userDb.C(USER_DB_PROFILE_COLLECTION)
	q = profileC.Find(bson.M{})
	it = q.Iter()

	userResult := db.User{}
	for it.Next(&userResult) {
		result.AccountNum += 1

		appQ := appC.Find(bson.M{
			"ownerid": userResult.Id,
		})
		if n, _ := appQ.Count(); n < 1 {
			result.AccountNotApplyNum += 1
		}
	}

	public.ResponseOkAsJson(resp, &result)
}