Ejemplo n.º 1
0
func handleViewStagingRecomms(resp http.ResponseWriter, req *http.Request) {
	user_id, _ := public.GetSessionUserId(req)

	stagingDb := public.GetNewStagingDatabase()
	defer stagingDb.Session.Close()

	recomms := stagingDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)
	q := recomms.Find(bson.M{
		"recommender": user_id,
	})
	var result []public.RecommView
	recomm_item := db.RecommEntity{}
	it := q.Iter()
	for it.Next(&recomm_item) {

		signed_url := ""
		if client, err := storage.GetNewStorageClient(); err == nil {
			expireTime := time.Now().Add(time.Duration(1) * time.Hour) //an hour
			signed_url, _ = client.GetNewSignedURL(string(recomm_item.Attachment), expireTime)
		}

		result = append(result, public.RecommView{
			Hash:         recomm_item.Hash,
			ApplyUser:    recomm_item.ApplyUser,
			Topic:        recomm_item.Topic,
			LastModified: recomm_item.LastModified,
			Content:      recomm_item.Content,
			Attachment:   signed_url,
		})
	}

	public.ResponseOkAsJson(resp, &result)
}
Ejemplo n.º 2
0
func removeStagingRecomm(resp http.ResponseWriter, req *http.Request) {

	user_id, _ := public.GetSessionUserId(req)
	vars := mux.Vars(req)
	hash := vars["hash"]

	stagingDb := public.GetNewStagingDatabase()
	defer stagingDb.Session.Close()

	recomm := stagingDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)
	q := recomm.Find(bson.M{
		"hash":        hash,
		"recommender": user_id,
	})
	recomm_result := db.RecommEntity{}
	if e := q.One(&recomm_result); e != nil {
		public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{
			Message: "No such recomm entry",
		})
		return
	}

	if e := recomm.RemoveId(recomm_result.Id); e != nil {
		public.LogE.Printf("Remove recomm entity failed: %s\n", e.Error())
		public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{
			Message: "Remove recomm failed",
		})
	} else {
		public.ResponseOkAsJson(resp, nil)
	}
}
Ejemplo n.º 3
0
func handleSubmitRecomm(resp http.ResponseWriter, req *http.Request) {

	user_id, _ := public.GetSessionUserId(req)
	user_perm, _ := public.GetSessionUserPermission(req)

	vars := mux.Vars(req)
	hash_str := vars["hash"]

	stagingDb := public.GetNewStagingDatabase()
	defer stagingDb.Session.Close()

	staging_recomm := stagingDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)

	q := staging_recomm.Find(bson.M{
		"hash": hash_str,
	})

	recomm_result := db.RecommEntity{}
	if e := q.One(&recomm_result); e != nil {
		public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{
			Message: "No such recomm entity",
		})
		return
	}

	// Permission check
	if recomm_result.Recommender != user_id && user_perm != public.USER_PERMISSION_GM {
		public.ResponseStatusAsJson(resp, 403, nil)
		return
	}

	// Migrate from staging db to application db
	staging_recomm.RemoveId(recomm_result.Id)

	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()

	recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)
	new_recomm := recomm_result
	new_recomm.Id = bson.NewObjectId()
	new_recomm.LastModified = time.Now()

	if e := recomm.Insert(new_recomm); e != nil {
		public.LogE.Printf("Error migrating recomm from staging db to application db: %s\n", e.Error())
		public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{
			Message: "Submit failed",
		})
	}
}
Ejemplo n.º 4
0
func getUserRecomms(resp http.ResponseWriter, req *http.Request) {
	user_id, _ := public.GetSessionUserId(req)

	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()

	forms := appDb.C(public.APPLICATION_DB_FORM_COLLECTION)
	q := forms.Find(bson.M{"ownerid": user_id}).Sort("-timestamp")
	it := q.Iter()

	form := db.ApplicationForm{}
	var recommList []public.RecommResult
	topicMap := make(map[public.TopicId]bool)
	for it.Next(&form) {
		if _, exist := topicMap[form.Topic]; exist {
			//Skip
			continue
		}

		recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)

		for _, h := range form.Recommendations {
			//Transform recommendation from hash to structures
			q := recomm.Find(bson.M{
				"hash": h,
			})

			if n, e := q.Count(); e == nil && n > 0 {
				r := db.Recomm{}
				if e := q.One(&r); e == nil {
					r := public.RecommResult{
						Recommender: r.Recommender,
						ApplyUser:   r.ApplyUser,
						Done:        r.Submitted,
						Hash:        h,
					}
					recommList = append(recommList, r)
				}
			}
		}

		topicMap[form.Topic] = true
	}

	public.ResponseOkAsJson(resp, &recommList)
}
Ejemplo n.º 5
0
func editStagingRecomm(resp http.ResponseWriter, req *http.Request) {

	user_id, _ := public.GetSessionUserId(req)
	vars := mux.Vars(req)
	hash := vars["hash"]

	stagingDb := public.GetNewStagingDatabase()
	defer stagingDb.Session.Close()

	recomm := stagingDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)
	q := recomm.Find(bson.M{
		"hash":        hash,
		"recommender": user_id,
	})
	recomm_result := db.RecommEntity{}
	if e := q.One(&recomm_result); e != nil {
		public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{
			Message: "No such recomm entry",
		})
		return
	}

	content := req.FormValue("content")
	attachment := req.FormValue("attachment")

	if len(content) > 0 {
		recomm_result.Content = content
		recomm_result.LastModified = time.Now()
	}

	if len(attachment) > 0 {
		recomm_result.Attachment = public.FileStoragePath(attachment)
		recomm_result.LastModified = time.Now()
	}

	if e := recomm.UpdateId(recomm_result.Id, &recomm_result); e != nil {
		public.LogE.Printf("Update recomm entity failed: %s\n", e.Error())
		public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{
			Message: "Update recomm failed",
		})
	} else {
		public.ResponseOkAsJson(resp, nil)
	}
}
Ejemplo n.º 6
0
func handleViewRecomm(resp http.ResponseWriter, req *http.Request) {
	user_id, _ := public.GetSessionUserId(req)
	user_perm, _ := public.GetSessionUserPermission(req)

	vars := mux.Vars(req)
	hash_str := vars["hash"]

	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()

	recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)
	q := recomm.Find(bson.M{
		"hash": hash_str,
	})

	recomm_result := db.RecommEntity{}
	if e := q.One(&recomm_result); e != nil {
		public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{
			Message: "No such recomm entity",
		})
		return
	}

	// Permission check
	if recomm_result.Recommender != user_id && user_perm != public.USER_PERMISSION_GM {
		public.ResponseStatusAsJson(resp, 403, nil)
		return
	}

	signed_url := ""
	if client, err := storage.GetNewStorageClient(); err == nil {
		expireTime := time.Now().Add(time.Duration(1) * time.Hour) //an hour
		signed_url, _ = client.GetNewSignedURL(string(recomm_result.Attachment), expireTime)
	}

	public.ResponseOkAsJson(resp, &public.RecommView{
		Hash:         recomm_result.Hash,
		ApplyUser:    recomm_result.ApplyUser,
		Topic:        recomm_result.Topic,
		LastModified: recomm_result.LastModified,
		Content:      recomm_result.Content,
		Attachment:   signed_url,
	})
}
Ejemplo n.º 7
0
func handleRecommDoorBell(resp http.ResponseWriter, req *http.Request) {
	_, user_err := public.GetSessionUserId(req)

	if user_err != nil {
		public.ResponseStatusAsJson(resp, 403, nil)
		return
	}

	user_perm, _ := public.GetSessionUserPermission(req)

	if !user_perm.ContainsPermission(public.USER_PERMISSION_RECOMM) {
		public.ResponseStatusAsJson(resp, 403, &public.SimpleResult{
			Message: "Not Recommender",
		})
		return
	}

	public.ResponseOkAsJson(resp, &public.SimpleResult{
		Message: "Ok",
	})
}
Ejemplo n.º 8
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)
	}
}
Ejemplo n.º 9
0
func handleFormView(resp http.ResponseWriter, req *http.Request) {
	userId, _ := public.GetSessionUserId(req)

	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()

	forms := appDb.C(public.APPLICATION_DB_FORM_COLLECTION)
	q := forms.Find(bson.M{
		"ownerid": userId,
	})
	if _, e := q.Count(); e != nil {
		public.LogE.Println("Query user form error: " + e.Error())
		public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{
			Message: "Error",
		})
	} else {

		var formResults []exportApplication
		form := db.ApplicationForm{}
		it := q.Iter()

		for it.Next(&form) {
			exportForm := exportApplication{}
			(&exportForm).fromDbApplication(&form, false)
			formResults = append(formResults, exportForm)
		}

		public.ResponseOkAsJson(resp, formResults)

		/*
			if client, err := storage.GetNewStorageClient(); err == nil {
				defer client.Close()
				var formResults []db.ApplicationForm
				form := db.ApplicationForm{}

				it := q.Iter()
				expireTime := time.Now().Add(time.Duration(1) * time.Hour) //an hour
				for it.Next(&form) {
					form.Id = bson.ObjectId("")
					form.OwnerId = bson.ObjectId("")

					//Handle the file objects
					if obj,e := client.GetNewSignedURL(form.ResearchPlan, expireTime); e == nil {
						form.ResearchPlan = obj
					}else{
						public.LogE.Println("Get object error: " + e.Error())
					}
					if obj,e := client.GetNewSignedURL(form.Transcript, expireTime); e == nil {
						form.Transcript = obj
					}else{
						public.LogE.Println("Get object error: " + e.Error())
					}
					if len(form.Others) > 0 {
						if obj,e := client.GetNewSignedURL(form.Others, expireTime); e == nil {
							form.Others = obj
						}else{
							public.LogE.Println("Get object error: " + e.Error())
						}
					}

					formResults = append(formResults, form)
				}

				public.ResponseOkAsJson(resp, formResults)
			}else{
				public.LogE.Println("Error getting storage client: " + err.Error())
				public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{
					Message: "Error",
				})
			}
		*/
	}
}
Ejemplo n.º 10
0
func handleFormSubmit(resp http.ResponseWriter, req *http.Request) {
	ownerId, _ := public.GetSessionUserId(req)

	form := db.ApplicationForm{
		OwnerId:   ownerId,
		Timestamp: time.Now(),

		Name:       req.FormValue("name"),
		School:     req.FormValue("school"),
		Department: req.FormValue("department"),
		Email:      req.FormValue("email"),
		Phone:      req.FormValue("phoneNumber"),
		Address:    req.FormValue("address"),
		FormalId:   req.FormValue("formalId"), //TODO: Verify

		Teacher:       req.FormValue("teacher"),
		ResearchArea:  req.FormValue("researchArea"),
		RelatedSkills: req.FormValue("relatedSkills"),

		ResearchPlan: req.FormValue("researchPlan"),
		Transcript:   req.FormValue("transcript"),
		Others:       req.FormValue("others"),
	}

	if topic, err := parseTopic(req); err != nil {
		public.LogE.Println(err.Error())
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Wrong form format",
		})
		return
	} else {
		form.Topic = public.TopicId(topic)
	}

	if grade, err := parseSchoolGrade(req); err != nil {
		public.LogE.Println(err.Error())
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Wrong form format",
		})
		return
	} else {
		form.SchoolGrade = grade
	}

	if birthday, err := parseBirthday(req); err != nil {
		public.LogE.Println(err.Error())
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Wrong form format",
		})
		return
	} else {
		form.Birthday = birthday
	}

	if classes, err := parseStudiedClasses(req); err != nil {
		public.LogE.Println(err.Error())
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Wrong form format",
		})
		return
	} else {
		form.ClassHistories = classes
	}

	if languages, err := parseLanguageAbility(req); err != nil {
		public.LogE.Println(err.Error())
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Wrong form format",
		})
		return
	} else {
		form.LangAbilities = languages
	}

	if average, ranking, err := parseAcademicGrades(req); err != nil {
		public.LogE.Println(err.Error())
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Wrong form format",
		})
		return
	} else {
		form.AcademicGrade = db.AcademicGrade{
			Average: average,
			Rank:    ranking,
		}
	}

	if letters, err := parseRecommendationLetters(req); err != nil {
		public.LogE.Println(err.Error())
		public.ResponseStatusAsJson(resp, 400, &public.SimpleResult{
			Message:     "Error",
			Description: "Wrong form format",
		})
		return
	} else {
		form.Recommendations = handleRecommendationLetters(letters, form.Name, form.Email)
	}

	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()

	forms := appDb.C(public.APPLICATION_DB_FORM_COLLECTION)
	if err := forms.Insert(&form); err != nil {
		public.LogE.Printf("Insert new form error: " + err.Error())
		public.ResponseStatusAsJson(resp, 500, &public.SimpleResult{
			Message:     "Error",
			Description: "Add Form Error",
		})
	} else {
		public.ResponseOkAsJson(resp, &public.SimpleResult{
			Message: "Success",
		})
	}
}
Ejemplo n.º 11
0
func handleLogin(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.GetSessionUserId(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
		}

		if err := public.SetUserSessionValue(req, resp, public.USER_ID_SESSION_KEY, user.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, user.Permission); err != nil {
			public.LogE.Printf("Error setting session user permission: %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
	}
}