예제 #1
0
//File saving routines
func saveFile(header *multipart.FileHeader, r io.Reader) (string, error) {
	if client, err := storage.GetNewStorageClient(); err == nil {
		h := public.NewHashString()
		objName := storage.PathJoin(storage.APPLICATIONS_FOLDER_NAME, h)
		//Determine the extension
		var ext string = ""
		if header != nil {
			if segs := strings.Split(header.Filename, "."); len(segs) > 1 {
				ext = "." + segs[len(segs)-1]
				objName = (objName + ext)
			}
		}

		obj := client.GetDefaultBucket().Object(objName)
		objWriter := obj.NewWriter(client.Ctx)

		_, err = io.Copy(objWriter, r)
		objWriter.Close()
		if err == nil {

			if attr, e := obj.Attrs(client.Ctx); attr != nil && e == nil {
				if mimeStr := mime.TypeByExtension(ext); len(mimeStr) > 0 {
					attr.ContentType = mimeStr
					obj.Update(client.Ctx, *attr)
				}
			}

			return objName, nil
		} else {
			return "", err
		}
	} else {
		return "", err
	}
}
예제 #2
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)
}
예제 #3
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,
	})
}
예제 #4
0
func handleReviewerProfile(resp http.ResponseWriter, req *http.Request) {
	userId, _ := public.GetSessionReviewerId(req)

	reviewerDb := public.GetNewReviewerDatabase()
	defer reviewerDb.Session.Close()

	profile := reviewerDb.C(REVIEWER_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 {
		reviewer := db.Reviewer{}
		q.One(&reviewer)

		r := public.ReviewerProfile{
			Email:    reviewer.BaseProfile.Email,
			Username: reviewer.BaseProfile.Username,
			FormalId: reviewer.BaseProfile.FormalId,

			Topics:      reviewer.Topics,
			Permissions: reviewer.Permissions,
		}

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

		public.ResponseOkAsJson(resp, &r)
	}
}
예제 #5
0
func handleReviewerRecommView(resp http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	hashStr := vars["recommHash"]

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

	recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)

	q := recomm.Find(bson.M{
		"hash": hashStr,
	})
	recommInstance := db.Recomm{}
	if err := q.One(&recommInstance); err != nil {
		public.ResponseStatusAsJson(resp, 404, &public.SimpleResult{
			Message:     "Error",
			Description: "Hash not found",
		})
		return
	}

	recommResult := reviewerRecommResult{
		Content: recommInstance.Content,
	}

	if len(recommInstance.Attachment) > 0 {
		//Create temp url
		if client, err := storage.GetNewStorageClient(); err == nil {
			expireTime := time.Now().Add(time.Duration(1) * time.Hour) //an hour
			if obj, e := client.GetNewSignedURL(recommInstance.Attachment, expireTime); e == nil {
				recommResult.AttachmentUrl = obj
			} else {
				public.LogE.Println("Get object error: " + e.Error())
			}
		}
	}

	public.ResponseOkAsJson(resp, &recommResult)
}
예제 #6
0
func (this *exportApplication) fromDbApplication(form *db.ApplicationForm, isReviewer bool) {
	this.Timestamp = form.Timestamp

	this.Name = form.Name
	this.School = form.School
	this.Department = form.Department
	this.SchoolGrade = form.SchoolGrade
	this.Birthday = form.Birthday
	this.FormalId = form.FormalId
	this.Phone = form.Phone
	this.Email = form.Email
	this.Address = form.Address

	this.Topic = form.Topic
	this.Teacher = form.Teacher
	this.ResearchArea = form.ResearchArea
	this.ClassHistories = form.ClassHistories
	this.RelatedSkills = form.RelatedSkills
	this.AcademicGrade = form.AcademicGrade
	this.LangAbilities = form.LangAbilities

	//Hash
	this.Hash = public.NewSecureHashString()

	//Extras
	//Transform file id to url
	if client, err := storage.GetNewStorageClient(); err == nil {

		expireTime := time.Now().Add(time.Duration(1) * time.Hour) //an hour
		if obj, e := client.GetNewSignedURL(form.ResearchPlan, expireTime); e == nil {
			this.ResearchPlan = obj
		} else {
			public.LogE.Println("Get object error: " + e.Error())
		}
		if obj, e := client.GetNewSignedURL(form.Transcript, expireTime); e == nil {
			this.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 {
				this.Others = obj
			} else {
				public.LogE.Println("Get object error: " + e.Error())
			}
		}
	} else {
		public.LogE.Printf("Error getting storage client")
	}

	appDb := public.GetNewApplicationDatabase()
	defer appDb.Session.Close()
	recomm := appDb.C(public.APPLICATION_DB_RECOMM_COLLECTION)
	var recommList []public.RecommResult

	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,
				}
				if isReviewer {
					r.Hash = h
				} else {
					r.Hash = ""
				}
				recommList = append(recommList, r)
			}
		}
	}
	this.Recommendations = recommList
}
예제 #7
0
func handleReviewRegister(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
		}

		reviewerDb := public.GetNewReviewerDatabase()
		defer reviewerDb.Session.Close()

		profile := reviewerDb.C(REVIEWER_DB_PROFILE_COLLECTION)
		q := profile.Find(bson.M{"baseprofile.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 {
			baseUser := db.User{
				Email:    email,
				Username: username,
				FormalId: formalId,
			}
			hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
			baseUser.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 {
						baseUser.Thumbnail = objName
					}
				}
			}

			newUser := db.Reviewer{
				BaseProfile: baseUser,
			}

			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.SetReviewerSessionValue(req, resp, public.REVIEWER_ID_SESSION_KEY, newUser.Id.Hex()); err != nil {
					public.LogE.Printf("Error setting session user id: %s\n", err.Error())
				}

				r := public.SimpleResult{
					Message:     "Register Successed",
					Description: email,
				}
				public.ResponseOkAsJson(resp, &r)
			}
		}
	}
}