Exemple #1
0
func DeleteImage(ctx context.Context) error {
	var currentUser, ok = ctx.Data()["user"].(m.User)
	if ok {
		imageId := ctx.FormValue("imageId")

		if imageId == "" {
			return goweb.API.Respond(ctx, 200, nil, []string{"You have to specify an image to be deleted."})
		}

		var image m.Image

		err := m.GetDB("Image").FindId(bson.ObjectIdHex(imageId)).One(&image)
		if err != nil {
			log.Error("DeleteImage, remove query " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"You have to specify an image to be deleted."})
		}
		if image.User.Hex() != currentUser.Id.Hex() {
			return goweb.API.Respond(ctx, 200, nil, []string{"You cannot delete this image."})
		} else {
			m.GetDB("Image").RemoveId(image.Id)
			err = os.Remove(image.Url)
		}

		return goweb.API.RespondWithData(ctx, "Image deleted.")
	} else {
		return goweb.API.Respond(ctx, 200, nil, []string{"Please log in to delete an images."})
	}
}
// GET /api/session
func (ctrl *SessionController) ReadMany(ctx context.Context) (err error) {
	session, _ := session_store.Get(ctx.HttpRequest(), session_name)
	if session.Values["username"] != nil {
		return goweb.API.RespondWithError(ctx, http.StatusBadRequest, "has session")
	}

	// check form value(not empty?)
	id := ctx.FormValue("id")
	passwd := ctx.FormValue("password")
	if id == "" || passwd == "" {
		return goweb.API.RespondWithError(ctx, http.StatusBadRequest, "not enough query")
	}

	// get userdata from database
	user, err := GetUser(id, passwd)
	if err != nil {
		return goweb.API.RespondWithError(ctx, http.StatusInternalServerError, "error on database")
	}

	if user == nil {
		return goweb.API.RespondWithError(ctx, http.StatusUnauthorized, "user not found")
	}

	session.Values["username"] = user.Name
	session.Save(ctx.HttpRequest(), ctx.HttpResponseWriter())
	return goweb.API.RespondWithData(ctx, nil)
}
Exemple #3
0
func GetPopularLocations(ctx context.Context) error {
	var query bson.M
	isPersonal, err := strconv.ParseBool(ctx.FormValue("personal"))
	if err != nil {
		isPersonal = false
	}
	if isPersonal {
		var result m.PopularLocations
		var currentUser, ok = ctx.Data()["user"].(m.User)
		if ok {
			query = bson.M{"user": currentUser.Id}
			if err := m.GetDB("RecommendUser").Find(query).One(&result); err != nil {
				//respond with empty arrays it no recommendations/popular location for current user
				result = m.PopularLocations{PopularMarkers: make([]m.Marker, 0), Recommendations: make([]m.Recommendation, 0)}
				//fmt.Printf("%v  %v", err, result)
			}
			return goweb.API.RespondWithData(ctx, result)
		}
	}
	var trendResult []m.TrendingAllUsersEntry
	var recomResult []m.Recommendation
	m.GetDB("TrendingAllUsers").Find(query).All(&trendResult)
	m.GetDB("RecommendAllUsers").Find(query).All(&recomResult)
	result := m.AllUsersTrendingAndRecom{Trend: trendResult, Recom: recomResult}
	return goweb.API.RespondWithData(ctx, result)
}
Exemple #4
0
// WithStatus writes the specified HTTP Status Code to the Context's ResponseWriter.
//
// If the Always200ParamName parameter is present, it will ignore the httpStatus argument,
// and always write net/http.StatusOK (200).
func (r *GowebHTTPResponder) WithStatus(ctx context.Context, httpStatus int) error {

	// check for always200
	if len(ctx.FormValue(Always200ParamName)) > 0 {
		// always return OK
		httpStatus = http.StatusOK
	}

	ctx.HttpResponseWriter().WriteHeader(httpStatus)
	return nil
}
func isSessionValid(ctx context.Context) bool {
	session, _ := session_store.Get(ctx.HttpRequest(), session_name)
	session_token := session.Values["token"]

	session.Values["token"] = ""
	session.Save(ctx.HttpRequest(), ctx.HttpResponseWriter())

	if session_token == "" || session_token != ctx.FormValue("token") {
		return false
	}
	return true
}
// GET /api/statuses
func (ctrl *StatusesController) ReadMany(ctx context.Context) (err error) {
	count, err := strconv.Atoi(ctx.FormValue("count"))
	if err != nil {
		count = 15
	}

	dat, err := GetStatuses(count)
	if err != nil {
		logger.Debug(err)
		return goweb.API.RespondWithError(ctx, http.StatusInternalServerError, "error on db")
	}

	return goweb.API.RespondWithData(ctx, dat)
}
Exemple #7
0
func ParseDateFromContext(prefix string, ctx context.Context) (time.Time, bool) {
	now := time.Now()

	if strings.Contains(prefix, "from") {
		now = now.AddDate(0, 0, -1)
	}
	if strings.Contains(prefix, "to") {
		now = now.AddDate(0, 0, 1)
	}

	anythingSelected := false

	year, err := strconv.Atoi(ctx.FormValue(prefix + "year"))
	if err != nil {
		year = now.Year()
	} else {
		anythingSelected = true
	}
	var month time.Month
	month_int, err := strconv.Atoi(ctx.FormValue(prefix + "month"))
	if err != nil {
		month = now.Month()
	} else {
		month = time.Month(month_int)
		anythingSelected = true
	}
	day, err := strconv.Atoi(ctx.FormValue(prefix + "day"))
	if err != nil {
		day = now.Day()
	} else {
		anythingSelected = true
	}
	hour, err := strconv.Atoi(ctx.FormValue(prefix + "hour"))
	if err != nil {
		hour = now.Hour()
	} else {
		anythingSelected = true
	}
	min, err := strconv.Atoi(ctx.FormValue(prefix + "min"))
	if err != nil {
		min = now.Minute()
	} else {
		anythingSelected = true
	}
	return time.Date(year, month, day, hour, min, 0, 0, time.UTC), anythingSelected
}
// GET /api/session
func (ctrl *SearchController) ReadMany(ctx context.Context) (err error) {
	query := ctx.FormValue("q")
	if query == "" {
		return goweb.API.RespondWithError(ctx, http.StatusUnauthorized, "not enough query")
	}

	count, err := strconv.Atoi(ctx.FormValue("count"))
	if err != nil {
		count = 10
	}

	statuses, err := SearchStatuses(query, count)
	if err != nil {
		logger.Debug(err)
		return goweb.API.RespondWithError(ctx, http.StatusInternalServerError, "error on db")
	}

	return goweb.API.RespondWithData(ctx, statuses)
}
// POST /api/statuses
func (ctrl *StatusesController) Create(ctx context.Context) (err error) {
	user := getUserNameFromCtx(ctx)
	if user == "" || !isSessionValid(ctx) {
		return goweb.API.RespondWithError(ctx, http.StatusUnauthorized, "not enough query")
	}

	text := ctx.FormValue("shout")
	if text == "" {
		return goweb.API.RespondWithError(ctx, http.StatusBadRequest, "not enough query")
	}

	err = CreateStatus(user, text)
	if err != nil {
		logger.Debug(err)
		return goweb.API.RespondWithError(ctx, http.StatusInternalServerError, "error on db")
	}

	return goweb.API.RespondWithData(ctx, nil)
}
Exemple #10
0
func GetVideos(ctx context.Context) error {
	var result []m.Video

	// Get the info from the context
	fromDate, fromDateExists := utils.ParseDateFromContext("from_", ctx)
	toDate, toDateExists := utils.ParseDateFromContext("to_", ctx)

	limit, err := strconv.Atoi(ctx.FormValue("limit"))
	if err != nil {
		limit = 5
	}

	skip, err := strconv.Atoi(ctx.FormValue("skip"))
	if err != nil {
		skip = 0
	}

	var currentUser, ok = ctx.Data()["user"].(m.User)
	isPersonal, err := strconv.ParseBool(ctx.FormValue("personal"))
	if err != nil {
		isPersonal = false
	}

	query := bson.M{}
	if ok && isPersonal {
		if fromDateExists || toDateExists {
			query["date"] = bson.M{"$gte": fromDate, "$lte": toDate}
			query["user"] = currentUser.Id
		} else {
			query["user"] = currentUser.Id
		}
	} else {
		isPersonal = false
		if fromDateExists || toDateExists {
			query["date"] = bson.M{"$gte": fromDate, "$lte": toDate}
		}
	}

	if !fromDateExists && !toDateExists {
		var lastVideo m.Image
		var oneQuery = bson.M{}
		if isPersonal {
			oneQuery["user"] = currentUser.Id
		}
		if err = m.GetDB("Video").Find(oneQuery).Sort("-date").One(&lastVideo); err == nil {
			query["date"] = bson.M{"$gte": lastVideo.Date.AddDate(0, 0, -1), "$lte": lastVideo.Date.AddDate(0, 0, 1)}
		}
	}

	if err := m.GetDB("Video").Find(query).Skip(skip).Limit(limit).All(&result); err != nil {
		log.Error("Failed to search for tracks: " + err.Error())
		return goweb.API.Respond(ctx, 200, nil, []string{"Failed to find the tracks."})
	}

	return goweb.API.RespondWithData(ctx, result)
}
// POST /api/user
func (ctrl *UserController) Create(ctx context.Context) (err error) {
	id := ctx.FormValue("id")
	screen_name := ctx.FormValue("screen_name")
	passwd := ctx.FormValue("password")
	if id == "" || screen_name == "" || passwd == "" {
		return goweb.API.RespondWithError(ctx, http.StatusBadRequest, "not enough query.")
	}

	err = CreateUser(id, screen_name, passwd)
	if err != nil {
		return goweb.API.RespondWithError(ctx, http.StatusInternalServerError, "error on database")
	}

	return goweb.API.RespondWithData(ctx, nil)
}
Exemple #12
0
func GetStats(ctx context.Context) error {
	var err error
	var pageType = ctx.FormValue("page")
	query := bson.M{}
	//barchartQuery := bson.M{}

	var totalFileSize int64 = 0

	var imageCount int = 0

	if pageType == "pstats" {

		var currentUser, ok = ctx.Data()["user"].(m.User)
		if ok {
			fmt.Println("USER OK")
			query["user"] = currentUser.Id
			//barchartQuery["user"] = currentUser.Id

			var identifier = currentUser.Username
			if identifier == "" {
				identifier = currentUser.Email
			}

			var dirs []os.FileInfo
			dirs, err = ioutil.ReadDir("../uploads/" + identifier)
			if err != nil {
				log.Error("Failed to read dir:" + err.Error())
			}
			fmt.Println("ID:" + identifier)
			for i := 0; i < len(dirs); i++ {
				totalFileSize += dirs[i].Size()
			}
			imageCount = len(dirs)
		} else {
			return goweb.API.Respond(ctx, 200, nil, []string{"Please log in to view your stats."})
		}
	} else {
		var subdirInfo []os.FileInfo
		var dirInfo []os.FileInfo

		dirInfo, err = ioutil.ReadDir("../uploads/")
		if err != nil {
			log.Error("Failed to read dir:" + err.Error())
		}

		for i := 0; i < len(dirInfo); i++ {
			if dirInfo[i].IsDir() {
				subdirInfo, err = ioutil.ReadDir("../uploads/" + dirInfo[i].Name())
				if err != nil {
					log.Error("Failed to read dir:" + err.Error())
				}
				for j := 0; j < len(subdirInfo); j++ {
					totalFileSize += subdirInfo[j].Size()
				}
				imageCount += len(subdirInfo)
			}
		}
	}

	// convert to MB
	var fileSizeInMB = strconv.FormatFloat((float64(totalFileSize) / 1000000), 'f', 2, 32)
	fmt.Println(fileSizeInMB)

	// Get the info from the context
	fromDate, fromDateExists := utils.ParseDateFromContext("from_", ctx)
	toDate, toDateExists := utils.ParseDateFromContext("to_", ctx)

	//Total number of users
	userCount, err := m.GetDB("User").Count()
	if err != nil {
		log.Error("Failed to find user count: " + err.Error())
	}

	//Total number of tracks
	trailCount, err := m.GetDB("Track").Find(query).Count()
	if err != nil {
		log.Error("Failed to find track count: " + err.Error())
	}

	// Query add date/time
	if fromDateExists || toDateExists {
		query["date"] = bson.M{"$gte": fromDate, "$lte": toDate}
	}

	//Filtered images and tracks by date/time and user
	filteredImageCount, err := m.GetDB("Image").Find(query).Count()
	if err != nil {
		log.Error("Failed to find image count: " + err.Error())
	}
	filteredTrackCount, err := m.GetDB("Track").Find(query).Count()
	if err != nil {
		log.Error("Failed to find track count: " + err.Error())
	}

	fmt.Print("FILTERED IMAGE AND TRACK COUNT: ")
	fmt.Print(filteredImageCount)
	fmt.Print(" ")
	fmt.Print(filteredTrackCount)

	fmt.Println("")
	fmt.Println("")

	// Barchart number of images
	var dDay, dMonth, dYear = getDifference(fromDate, toDate)

	var imageCurrentCount int
	var imageCountBarchartValues []int
	var gpsCurrentCount int
	var gpsCountBarchartValues []int
	var currentLabel string
	var barchartLabels []string

	var nextDate, endNextDate time.Time

	var February = leapYearDays(fromDate.Year())
	var months = [13]int{0, 31, February, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

	if dYear < 1 {
		if dMonth < 1 { // days view

			for i := 0; i <= dDay; i++ {

				if i == 0 {
					nextDate, endNextDate = getDates(fromDate, 0, 0)
				}
				query["date"] = bson.M{"$gte": nextDate, "$lte": endNextDate}

				imageCurrentCount, err = m.GetDB("Image").Find(query).Count()
				if err != nil {
					log.Error("Failed to find image count: " + err.Error())
				}
				imageCountBarchartValues = append(imageCountBarchartValues, imageCurrentCount)

				gpsCurrentCount, err = m.GetDB("Track").Find(query).Count()
				if err != nil {
					log.Error("Failed to find gps count: " + err.Error())
				}
				gpsCountBarchartValues = append(gpsCountBarchartValues, gpsCurrentCount)

				currentLabel = strconv.Itoa(nextDate.Day()) + " " + nextDate.Month().String() + " " + strconv.Itoa(nextDate.Year())
				barchartLabels = append(barchartLabels, currentLabel)

				nextDate, endNextDate = getDates(nextDate.AddDate(0, 0, 1), 0, 0)
			}

		} else { // months view

			for i := 0; i <= dMonth; i++ {

				if i == 0 { //first third
					nextDate, endNextDate = getDates(fromDate, 0, months[int(fromDate.Month())])

				} else if i == dMonth { //last third
					nextDate = nextDate.AddDate(0, 1, 1-nextDate.Day())
					nextDate, endNextDate = getDates(nextDate, 0, toDate.Day())

				} else { // everything else from the beginning to the end of month
					nextDate = nextDate.AddDate(0, 1, 1-nextDate.Day())
					mEnd := months[int(nextDate.Month())]
					nextDate, endNextDate = getDates(nextDate, 0, mEnd)
				}

				query["date"] = bson.M{"$gte": nextDate, "$lte": endNextDate}

				imageCurrentCount, err = m.GetDB("Image").Find(query).Count()
				if err != nil {
					log.Error("Failed to find image count: " + err.Error())
				}
				imageCountBarchartValues = append(imageCountBarchartValues, imageCurrentCount)

				gpsCurrentCount, err = m.GetDB("Track").Find(query).Count()
				if err != nil {
					log.Error("Failed to find gps count: " + err.Error())
				}
				gpsCountBarchartValues = append(gpsCountBarchartValues, gpsCurrentCount)

				currentLabel = nextDate.Month().String() + " " + strconv.Itoa(nextDate.Year())
				barchartLabels = append(barchartLabels, currentLabel)

			}
		}

	} else { // years view

		for i := 0; i <= dYear; i++ {

			if i == 0 { //first third
				nextDate, endNextDate = getDates(fromDate, 12, months[int(fromDate.Month())]) //31?

			} else if i == dMonth { //last third
				nextDate = nextDate.AddDate(1, 1-int(nextDate.Month()), 1-nextDate.Day())
				nextDate, endNextDate = getDates(nextDate, int(toDate.Month()), toDate.Day())

			} else { // everything else from the beginning to the end of year
				nextDate = nextDate.AddDate(1, 1-int(nextDate.Month()), 1-nextDate.Day())
				nextDate, endNextDate = getDates(nextDate, 12, months[int(nextDate.Month())]) //31?
			}

			query["date"] = bson.M{"$gte": nextDate, "$lte": endNextDate}

			imageCurrentCount, err = m.GetDB("Image").Find(query).Count()
			if err != nil {
				log.Error("Failed to find image count: " + err.Error())
			}
			imageCountBarchartValues = append(imageCountBarchartValues, imageCurrentCount)

			gpsCurrentCount, err = m.GetDB("Track").Find(query).Count()
			if err != nil {
				log.Error("Failed to find gps count: " + err.Error())
			}
			gpsCountBarchartValues = append(gpsCountBarchartValues, gpsCurrentCount)

			currentLabel = nextDate.Month().String() + " " + strconv.Itoa(nextDate.Year())
			barchartLabels = append(barchartLabels, currentLabel)
		}

	}

	var stats = []int{userCount, imageCount, trailCount, filteredImageCount, filteredTrackCount}
	var result []interface{} = []interface{}{imageCountBarchartValues, barchartLabels, gpsCountBarchartValues, stats, fileSizeInMB}

	return goweb.API.RespondWithData(ctx, result)
}
Exemple #13
0
func GetTrails(ctx context.Context) error {
	var result []m.Track

	// Get the info from the context
	isHeatmap, err := strconv.ParseBool(ctx.FormValue("heatmap"))
	if err != nil {
		isHeatmap = false
	}

	isPersonal, err := strconv.ParseBool(ctx.FormValue("personal"))
	if err != nil {
		isPersonal = false
	}

	fromDate, fromDateExists := utils.ParseDateFromContext("from_", ctx)
	toDate, toDateExists := utils.ParseDateFromContext("to_", ctx)

	if !isPersonal {
		err = m.GetDB("Track").Find(bson.M{}).All(&result)

	} else if isPersonal {
		var query bson.M
		var currentUser, ok = ctx.Data()["user"].(m.User)
		if ok && !fromDateExists && !toDateExists {
			query = bson.M{}
			query["user"] = currentUser.Id
			err = m.GetDB("Track").Find(query).All(&result)

		} else if ok && fromDateExists && toDateExists {
			query = bson.M{"user": currentUser.Id, "date": bson.M{"$gte": fromDate, "$lte": toDate}}
			err = m.GetDB("Track").Find(query).All(&result)

		}
	}
	if !isHeatmap {
		mapName := "GpsTrails"

		var buffer bytes.Buffer

		buffer.WriteString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://earth.google.com/kml/2.0\">\n<Document>\n<name>")
		buffer.WriteString(mapName)
		buffer.WriteString("</name>\n<description>Glasgow Memories Server</description>\n")
		for i := 0; i < len(color); i++ {

			buffer.WriteString("<Style id=\"line")
			buffer.WriteString(strconv.Itoa(i + 1))
			buffer.WriteString("\">\n<LineStyle>\n<color>")
			buffer.WriteString(color[i%len(color)])
			buffer.WriteString("</color>\n<width>4</width>\n</LineStyle>\n</Style>\n\n")
		}

		for i := 0; i < len(result); i++ {
			buffer.WriteString("<Placemark>\n<name>Track ")
			buffer.WriteString(result[i].Date.String())
			buffer.WriteString("</name>\n<styleUrl>#line")
			buffer.WriteString(strconv.Itoa(utils.GetStyle(strings.Split(result[i].Date.String()[0:10], "-"), len(color)) + 1))
			buffer.WriteString("</styleUrl>\n<LineString>\n<altitudeMode>relative</altitudeMode>\n<coordinates>\n")
			for j := 0; j < len(result[i].Coordinates); j++ {
				buffer.WriteString(result[i].Coordinates[j].Lon + "," + result[i].Coordinates[j].Lat + ",0\n")
			}
			buffer.WriteString("</coordinates>\n</LineString>\n</Placemark>\n")
		}
		buffer.WriteString("</Document>\n")
		buffer.WriteString("</kml>\n")
		ctx.HttpResponseWriter().Header().Set("Content-Type", "application/vnd.google-earth.kml+xml")
		ctx.HttpResponseWriter().Write([]byte(buffer.String()))
		return nil
		// return goweb.Respond.With(ctx, http.StatusOK, []byte(buffer.String()))
	} else {
		var formattedData [][]string
		for i := 0; i < len(result); i++ {
			for j := 0; j < len(result[i].Coordinates); j++ {
				formattedData = utils.Append(formattedData, []string{result[i].Coordinates[j].Lat, result[i].Coordinates[j].Lon})
			}
		}
		return goweb.API.RespondWithData(ctx, formattedData)
	}
}
Exemple #14
0
func GetImages(ctx context.Context) error {
	var result []m.Image

	// Get the info from the context
	fromDate, fromDateExists := utils.ParseDateFromContext("from_", ctx)
	toDate, toDateExists := utils.ParseDateFromContext("to_", ctx)

	searchType := ctx.FormValue("upload")
	if searchType != "" {
		searchType = "uploaded"
	} else {
		searchType = "date"
	}

	limit, err := strconv.Atoi(ctx.FormValue("limit"))
	if err != nil {
		limit = 20
	}

	skip, err := strconv.Atoi(ctx.FormValue("skip"))
	if err != nil {
		skip = 0
	}

	var currentUser, ok = ctx.Data()["user"].(m.User)
	isPersonal, err := strconv.ParseBool(ctx.FormValue("personal"))
	if err != nil {
		isPersonal = false
	}
	query := bson.M{}
	if ok && isPersonal {
		if fromDateExists || toDateExists {
			query[searchType] = bson.M{"$gte": fromDate, "$lte": toDate}
			query["user"] = currentUser.Id
		} else {
			query["user"] = currentUser.Id
		}
	} else {
		isPersonal = false
		if fromDateExists || toDateExists {
			query[searchType] = bson.M{"$gte": fromDate, "$lte": toDate}
		}
	}

	addLocation := true
	var lat, long, radius float64
	rad, err := strconv.Atoi(ctx.FormValue("radius"))
	if err != nil {
		addLocation = false
	}
	if addLocation {
		radius = float64(rad)
		lat, err = strconv.ParseFloat(ctx.FormValue("lat"), 64)
		if err != nil {
			addLocation = false
		}
		long, err = strconv.ParseFloat(ctx.FormValue("log"), 64)
		if err != nil {
			addLocation = false
		}
	}

	if addLocation {
		query["lat"] = bson.M{"$gt": lat - radius, "$lt": lat + radius}
		query["log"] = bson.M{"$gt": long - radius, "$lt": long + radius}
	}

	showAll := ctx.FormValue("allImages")
	if showAll == "" {
		query["show"] = true
	}
	keyMoments := ctx.FormValue("keyMoments")
	if keyMoments != "" {
		query["processed"] = true
	}

	if err = m.GetDB("Image").Find(query).Sort("-" + searchType).Skip(skip).Limit(limit).All(&result); err != nil {
		log.Error("Failed to search for images: " + err.Error())
		return goweb.API.Respond(ctx, 200, nil, []string{"Failed to find the images."})
	}
	return goweb.API.RespondWithData(ctx, result)
}
Exemple #15
0
func Login(ctx context.Context) error {
	var currentUser, ok = ctx.Data()["user"].(m.User)
	if ok {
		return goweb.API.RespondWithData(ctx, currentUser.Token)
	} else {
		username := ctx.FormValue("username")
		password := ctx.FormValue("password")

		// Check or basic auth header
		authHeader := ctx.HttpRequest().Header.Get("Authorization")
		if len(authHeader) > 0 {
			info, err := base64.StdEncoding.DecodeString(strings.Split(authHeader, " ")[1])
			if err == nil {
				decryptedInfo := strings.Split(string(info), ":")
				username = decryptedInfo[0]
				password = decryptedInfo[1]
			}
		}

		if len(username) < 3 || len(password) < 6 {
			return goweb.API.Respond(ctx, 200, nil, []string{"Invalid data supplied, please fill all fields."})
		}

		user := m.User{}
		query := bson.M{}
		if strings.Contains(username, "@") {
			query["username"] = username
		} else {
			query["email"] = username
		}
		err := m.GetDB("User").Find(query).One(&user)
		if err != nil {
			log.Error("Error in find user on login " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"No such username, please register."})
		}
		passport := m.Passport{}
		err = m.GetDB("Passport").Find(bson.M{"provider": "local", "user": user.Id}).One(&passport)
		if err != nil {
			log.Error("Error in find user passport on login " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"You have registered through Facebook."})
		}

		err = bcrypt.CompareHashAndPassword([]byte(passport.Password), []byte(password))
		if err != nil {
			return goweb.API.Respond(ctx, 200, nil, []string{"Incorrect password."})
		}
		log.Info("User found on local login")
		if user.Token == "" || user.TokenUpdate.Before(time.Now().AddDate(0, 0, -1)) {
			var token = nonce.NewToken()
			nonce.MarkToken(token)
			user.Token = token
			user.TokenUpdate = time.Now()

			err := m.GetDB("User").UpdateId(user.Id, user)
			if err != nil {
				log.Error("Failed to update token: " + err.Error())
			}
		}
		ctx.HttpResponseWriter().Header().Add("cookie", "token="+user.Token)
		return goweb.API.RespondWithData(ctx, user.Token)
	}
}
Exemple #16
0
func Register(ctx context.Context) error {
	var currentUser, ok = ctx.Data()["user"].(m.User)
	if ok {
		return goweb.API.RespondWithData(ctx, currentUser.Token)
	} else {
		username := ctx.FormValue("username")
		email := ctx.FormValue("email")
		password := ctx.FormValue("password")

		// Check or basic auth header
		authHeader := ctx.HttpRequest().Header.Get("Authorization")
		if len(authHeader) > 0 {
			info, err := base64.StdEncoding.DecodeString(strings.Split(authHeader, " ")[1])
			if err == nil {
				decryptedInfo := strings.Split(string(info), ":")
				username = decryptedInfo[0]
				password = decryptedInfo[1]
				email = decryptedInfo[2]
			}
		}

		if len(username) < 3 {
			return goweb.API.Respond(ctx, 200, nil, []string{"The username has to be at least 4 characters long."})
		}
		if len(email) == 0 {
			return goweb.API.Respond(ctx, 200, nil, []string{"Please supply an email address."})
		}

		err := utils.CheckValidPassword(password)
		if err != nil {
			return goweb.API.Respond(ctx, 200, nil, []string{err.Error()})
		}

		var oldUser m.User
		err = m.GetDB("User").Find(bson.M{"username": username}).One(&oldUser)
		if err == nil {
			log.Debug("Username already taken.")
			return goweb.API.Respond(ctx, 200, nil, []string{"Username already taken."})
		}

		var token = nonce.NewToken()
		nonce.MarkToken(token)
		newUser := m.User{bson.NewObjectId(), username, email, true, token, time.Now()}
		err = m.GetDB("User").Insert(&newUser)
		if err != nil {
			log.Error("Error on local registration, new user: "******"Failed to register."})
		}

		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 10)

		err = m.GetDB("Passport").Insert(&m.Passport{bson.NewObjectId(), newUser.Id, string(hashedPassword), "local", "", "", ""})
		if err != nil {
			log.Error("Error on local registration, new user passport: " + err.Error())
			m.GetDB("User").RemoveId(newUser.Id)
			return goweb.API.Respond(ctx, 200, nil, []string{"Failed to create your new passport."})
		}
		log.Info("New user registered local")
		return goweb.API.RespondWithData(ctx, newUser.Token)
	}
}