Пример #1
0
// UserLogin Check Login
func UserLogin(w http.ResponseWriter, r *http.Request, proute routes.Proute) {

	time.Sleep(1 * time.Second) // limit rate

	l := proute.Json.(*Userlogin)

	tx, err := db.DB.Beginx()
	if err != nil {
		log.Panicln("Can't start transaction for creating a new user")
		return
	}

	user := model.User{
		Username: l.Username,
	}

	err = user.Get(tx)
	if err != nil {
		log.Println("Login failed for user :"******"(can't find this username)")
		tx.Rollback()
		ArkeoError(w, 401, "Bad Username/Password")
		return
	}

	// test login
	ok := user.Login(l.Password)
	if !ok {
		log.Println("Login failed for user :"******"(password mismatch)")
		tx.Rollback()
		ArkeoError(w, 401, "Bad Username/Password")
		return
	}

	user.Password = "" // immediatly erase password field

	log.Println("Login ", user.Username, " => ", ok)

	token, s := session.NewSession()
	s.Values["user_id"] = user.Id
	s.Values["user"] = user

	a, err := loginAnswer(w, tx, user, token)
	if err != nil {
		log.Println("Login answer build failed : ", err)
		tx.Rollback()
		return
	}

	err = tx.Commit()
	if err != nil {
		userSqlError(w, err)
		return
	}

	j, err := json.Marshal(a)
	w.Write(j)
}
Пример #2
0
// UserLogout will destroy it's session
func UserLogout(w http.ResponseWriter, r *http.Request, proute routes.Proute) {
	time.Sleep(1 * time.Second) // limit rate

	u, ok := proute.Session.Get("user")
	if ok {
		user, ok := u.(model.User)
		log.Println("Logout ", user.Username, " => ", ok)
	}

	token := r.Header.Get("Authorization")
	session.DestroySession(token)

	tx, err := db.DB.Beginx()
	if err != nil {
		log.Panicln("Can't start transaction for creating a new user")
		return
	}

	user := model.User{
		Id: 0,
	}

	err = user.Get(tx)
	user.Password = "" // immediatly erase password field

	if err != nil {
		log.Println("Failed to load anonymous user ")
		tx.Rollback()
		ArkeoError(w, 401, "Bad thing appned")
		return
	}

	log.Println("Logout ", user.Username)

	token, s := session.NewSession()
	s.Values["user_id"] = user.Id
	s.Values["user"] = user

	a, err := loginAnswer(w, tx, user, token)
	if err != nil {
		log.Println("Login answer build failed : ", err)
		tx.Rollback()
		return
	}

	err = tx.Commit()
	if err != nil {
		userSqlError(w, err)
		return
	}

	j, err := json.Marshal(a)
	w.Write(j)
}
Пример #3
0
func main() {
	fmt.Println("test")

	tx, err := db.DB.Beginx()
	if err != nil {
		log.Panicln("Can't start transaction")
		return
	}

	var u1 model.User

	u1.Id = 1
	err = u1.Get(tx)
	if err != nil {
		log.Println("paf, u.Get: ", err)
	}

	//u1.Password = "******"
	ok, err := u1.Login(tx)
	if err != nil {
		log.Println("paf, u.Login: "******"Login OK")
	} else {
		log.Println("Login BAD")
	}

	fmt.Println("User: "******"paf, u.GetGroups: ", err)
	}

	permissions, err := u1.GetPermissions(tx)
	if err != nil {
		log.Println("paf, u.GetPermissions: ", err)
	}
	fmt.Println("permissions : ", permissions)

	ok, err = u1.HavePermissions(tx, "PermToLearn", "PermToSpeack")
	if err != nil {
		log.Println("paf, u.HavePermissions: ", err)
	}
	fmt.Println("Have ? : ", ok)

	newgroups := []model.Group{
		{
			Id: 2,
		},
		{
			Id: 3,
		},
	}
	err = newgroups[0].Get(tx)
	if err != nil {
		log.Println("paf1, u.GetGroups: ", err)
	}
	err = newgroups[1].Get(tx)
	if err != nil {
		log.Println("paf2, u.GetGroups: ", err)
	}

	fmt.Println("Groups: ", groups)
	fmt.Println("New Groups: ", newgroups)

	err = u1.SetGroups(tx, newgroups)
	if err != nil {
		log.Println("paf, u.SetGroups: ", err)
	}

	groups, err = u1.GetGroups(tx)
	if err != nil {
		log.Println("paf, u.GetGroups: ", err)
	}
	fmt.Println("Groups: ", groups)

	err = tx.Commit()
	if err != nil {
		if err, ok := err.(*pq.Error); ok {
			log.Println("commit user failed, pq error:", err.Code.Name())
		} else {
			log.Println("commit user failed !", err)
		}
		return
	}

}
Пример #4
0
func handledRoute(myroute *Route, rw http.ResponseWriter, r *http.Request) {

	start := time.Now()

	// debug transactions count
	count_before := 0
	db.DB.Get(&count_before, "SELECT count(*) from pg_stat_activity where state = 'idle in transaction'")

	defer func() {
		count_end := 0
		db.DB.Get(&count_end, "SELECT count(*) from pg_stat_activity where state = 'idle in transaction'")

		log.Println("idle in transaction : ", count_before, " => ", count_end)
	}()

	// session
	token := r.Header.Get("Authorization")
	log.Println("token ", token)
	s := session.GetSession(token)

	log.Print("user id from session : ", s.GetIntDef("user_id", -1))

	// Retrieve user id from session
	user := model.User{}
	user.Id = s.GetIntDef("user_id", 0)

	// Open a transaction to load the user from db
	tx, err := db.DB.Beginx()
	if err != nil {
		log.Panicln("Can't start transaction for loading user")
		ServerError(rw, 500, "Can't start transaction for loading user")
		return
	}

	// get langs
	lang1 := model.Lang{
		Isocode: "en",
	}
	lang2 := model.Lang{
		Isocode: "fr",
	}

	if _lang1, err := r.Cookie("arkeogis_user_lang_1"); err == nil {
		lang1.Isocode = _lang1.Value
	}
	if _lang2, err := r.Cookie("arkeogis_user_lang_2"); err == nil {
		lang2.Isocode = _lang2.Value
	}

	err = lang1.Get(tx)
	if err != nil {
		lang1.Isocode = "en"
		err = lang1.Get(tx)
		if err != nil {
			fmt.Println("can't load lang1 !")
		}
	}

	err = lang2.Get(tx)
	if err != nil {
		lang2.Isocode = "fr"
		err = lang2.Get(tx)
		if err != nil {
			fmt.Println("can't load lang2 !")
		}
	}

	fmt.Println("langs: ", lang1, lang2)

	// Retrieve the user from db
	user.Get(tx)
	log.Println("user is : ", user.Username)
	s.Set("user", user)

	restlog.WriteString(fmt.Sprintf(`[%s][%s] %s %s %s %s`+"\n", start.Format(time.RFC3339), user.Username, r.RemoteAddr, r.Method, r.URL.Path, myroute.Method))

	// Check global permsissions
	permok := true
	ok, err := user.HaveAtLeastOnePermission(tx, myroute.Permissions...)
	if err != nil {
		log.Println("user.HaveAtLeastOnePermission failed : ", err)
		permok = false
	} else if ok == false {
		log.Println("user has no permissions : ", myroute.Permissions)
		permok = false
	}

	// Close the transaction
	err = tx.Commit()
	if err != nil {
		if err, ok := err.(*pq.Error); ok {
			log.Println("commit while getting session user failed, pq error:", err.Code.Name())
		} else {
			log.Println("commit while getting session user failed !", err)
		}
		ServerError(rw, 500, "Can't commit transaction")
		return
	}

	// Print a log
	log.Printf("[%s] %s %s ; authorized: %t\n", user.Username, myroute.Method, myroute.Path, permok)
	if !permok {
		ServerError(rw, 403, "unauthorized")
		return
	}

	o := decodeContent(myroute, rw, r, s)
	if o != nil {
		errors := sanitizer.SanitizeStruct(o, "json")
		if len(errors) > 0 {
			Errors(rw, errors)
			return
		}
	}

	params := decodeParams(myroute, rw, r)
	if params != nil {
		log.Println("params    : ", params)
		errors := sanitizer.SanitizeStruct(params, "params")
		log.Println("Sanitized : ", params)
		if len(errors) > 0 {
			Errors(rw, errors)
			return
		}
	}

	proute := Proute{
		Json:    o,
		Params:  params,
		Session: s,
		Lang1:   lang1,
		Lang2:   lang2,
	}

	myroute.Func(rw, r, proute)

}
Пример #5
0
// userSet is for UserCreate or UserUpdate
func userSet(w http.ResponseWriter, r *http.Request, proute routes.Proute, create bool) {

	u := proute.Json.(*Usercreate)

	// hack overrides
	//u.User.Password = u.Password

	// hack for city
	u.City_geonameid = u.CityAndCountry.City.Geonameid
	log.Println("city : ", u.City_geonameid)

	tx, err := db.DB.Beginx()
	if err != nil {
		log.Println("1")
		userSqlError(w, err)
		return
	}

	_me, ok := proute.Session.Get("user")
	if !ok {
		log.Println("userSet: can't get user in session...", _me)
		_ = tx.Rollback()
		return
	}

	me, ok := _me.(model.User)
	if !ok {
		log.Println("userSet: can't cast user...", _me)
		_ = tx.Rollback()
		return
	}

	permAdminUsers, err := me.HavePermissions(tx, "adminusers")
	if err != nil {
		tx.Rollback()
		userSqlError(w, err)
		return
	}

	if create || u.User.Id != me.Id {
		if !permAdminUsers {
			tx.Rollback()
			routes.ServerError(w, 403, "unauthorized")
			return
		}
	}

	// password
	if len(u.Password) > 0 {

		if len(u.Password) < 7 {
			tx.Rollback()
			routes.FieldError(w, "json.password", "password", "USER.FIELD_PASSWORD.T_CHECK_LENGTH")
			return
		}

		err = u.User.MakeNewPassword(u.Password)
		if err != nil {
			fmt.Println("password generate failed")
			tx.Rollback()
			userSqlError(w, err)
			return
		}
	}

	// photo...
	if u.File != nil {
		photo := model.Photo{
			Photo: string(u.File.Content),
		}
		err = photo.Create(tx)
		if err != nil {
			log.Println("1")
			userSqlError(w, err)
			tx.Rollback()
			return
		}
		u.Photo_id = photo.Id
	}

	// save the user
	if create {
		err = u.Create(tx)
	} else {
		tmpuser := model.User{
			Id: u.Id,
		}
		err = tmpuser.Get(tx)
		if err != nil {
			log.Println("can't get user for update", err)
			userSqlError(w, err)
			tx.Rollback()
			return
		}

		if !permAdminUsers { // in this case, we update tmpuser with only authorized fields
			// if we set a new password
			if len(u.User.Password) != 0 {
				tmpuser.Password = u.User.Password
			}

			// authorized self modified user field
			tmpuser.Username = u.User.Username
			tmpuser.Firstname = u.User.Firstname
			tmpuser.Lastname = u.User.Lastname
			tmpuser.First_lang_isocode = u.User.First_lang_isocode
			tmpuser.Second_lang_isocode = u.User.Second_lang_isocode
			tmpuser.Description = u.User.Description
			tmpuser.Email = u.User.Email
			tmpuser.City_geonameid = u.User.City_geonameid

			err = tmpuser.Update(tx)
		} else {
			// if we don't set a new password, we take it back from the db
			if len(u.User.Password) == 0 {
				u.User.Password = tmpuser.Password
			}

			log.Println("updating user id : ", u.Id, u)
			err = u.Update(tx)
		}
	}
	if err != nil {
		log.Println("2")
		userSqlError(w, err)
		tx.Rollback()
		return
	}

	// save the companies
	var companies []model.Company
	for _, form_company := range u.Companies {
		if form_company.Id > 0 {
			form_company.City_geonameid = form_company.CityAndCountry.City.Geonameid
			log.Println("updating company : ", form_company.Company)
			err = form_company.Update(tx)
			if err != nil {
				log.Println("error while updating a company", err)
				tx.Rollback()
				userSqlError(w, err)
				return
			}
			companies = append(companies, form_company.Company)
		} else if len(form_company.Name) > 0 {
			form_company.City_geonameid = form_company.CityAndCountry.City.Geonameid
			log.Println("creating company : ", form_company.Company)
			err = form_company.Create(tx)
			if err != nil {
				log.Println("error while adding a company", err)
				tx.Rollback()
				userSqlError(w, err)
				return
			}
			companies = append(companies, form_company.Company)
		}
	}

	err = u.SetCompanies(tx, companies)
	if err != nil {
		log.Println("7")
		tx.Rollback()
		userSqlError(w, err)
		return
	}

	if permAdminUsers {
		// save the groups
		err = u.SetGroups(tx, u.Groups)
		if err != nil {
			log.Println("set groups")
			tx.Rollback()
			userSqlError(w, err)
			return
		}
	}

	err = tx.Commit()
	if err != nil {
		log.Println("8")
		userSqlError(w, err)
		return
	}

	j, err := json.Marshal("ok")
	w.Write(j)
}