Example #1
0
//-----------------------------------------------------------------------------
func (this *UserController) Login(userId string) {
	if !this.isAdmin() {
		http.Redirect(this.Response, this.Request, "/", http.StatusForbidden)
		return
	}

	id, err := strconv.Atoi(userId)
	if utils.HandleErr("[UserController::Login] user_id Atoi: ", err, this.Response) {
		return
	}

	if !db.IsExists("users", []string{"id"}, []interface{}{id}) {
		http.Error(this.Response, "Have not such user with the id", http.StatusInternalServerError)
		return
	}

	sid := utils.GetRandSeq(HASH_SIZE)
	params := map[string]interface{}{"sid": sid, "enabled": true}
	where := map[string]interface{}{"id": id}

	this.GetModel("users").Update(this.isAdmin(), id, params, where)
	sessions.SetSession(this.Response, map[string]interface{}{"sid": sid})

	http.Redirect(this.Response, this.Request, "/usercontroller/showcabinet", 200)
}
func (this *RegistrationController) Register(login, password, email, role string) (result string, regId int) {
	result = "ok"
	salt := strconv.Itoa(int(time.Now().Unix()))
	pass := utils.GetMD5Hash(password + salt)

	passHasInvalidChars := false
	for i := 0; i < len(password); i++ {
		if strconv.IsPrint(rune(password[i])) == false {
			passHasInvalidChars = true
			break
		}
	}

	if db.IsExists("users", []string{"login"}, []interface{}{login}) == true {
		result = "loginExists"

	} else if !utils.MatchRegexp("^[a-zA-Z0-9]{2,36}$", login) {
		result = "badLogin"

	} else if !utils.MatchRegexp("^.{6,36}$", password) || passHasInvalidChars {
		result = "badPassword"

		// } else if bad email {

	} else {
		token := utils.GetRandSeq(HASH_SIZE)

		if !mailer.SendConfirmEmail(login, email, token) {
			return "badEmail", -1
		}

		var userId int
		this.GetModel("users").
			LoadModelData(map[string]interface{}{
				"login":   login,
				"pass":    pass,
				"salt":    salt,
				"role":    role,
				"token":   token,
				"enabled": false}).
			QueryInsert("RETURNING id").
			Scan(&userId)

		var faceId int
		this.GetModel("faces").
			LoadModelData(map[string]interface{}{"user_id": userId}).
			QueryInsert("RETURNING id").
			Scan(&faceId)

		this.GetModel("registrations").
			LoadModelData(map[string]interface{}{"face_id": faceId, "event_id": 1, "status": false}).
			QueryInsert("RETURNING id").
			Scan(&regId)

		return result, regId
	}

	return result, -1
}
Example #3
0
func (this *UserController) SendEmailWellcomeToProfile() {
	if !this.isAdmin() {
		http.Redirect(this.Response, this.Request, "/", http.StatusForbidden)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if utils.HandleErr("[UserController::SendEmailWellcomeToProfile]: ", err, this.Response) {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	userId, err := strconv.Atoi(request["user_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	query := `SELECT param_values.value
        FROM param_values
        INNER JOIN registrations ON registrations.id = param_values.reg_id
        INNER JOIN params ON params.id = param_values.param_id
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE params.id in (4, 5, 6, 7) AND users.id = $1 ORDER BY params.id;`
	data := db.Query(query, []interface{}{userId})

	if len(data) < 4 {
		utils.SendJSReply(map[string]interface{}{"result": "Нет регистрационных данных пользователя."}, this.Response)
		return
	}

	to := data[1].(map[string]interface{})["value"].(string) + " "
	to += data[2].(map[string]interface{})["value"].(string) + " "
	to += data[3].(map[string]interface{})["value"].(string)
	email := data[0].(map[string]interface{})["value"].(string)

	token := utils.GetRandSeq(HASH_SIZE)
	if !mailer.SendEmailWellcomeToProfile(to, email, token) {
		utils.SendJSReply(map[string]interface{}{"result": "Проверьте правильность email."}, this.Response)
		return
	}

	params := map[string]interface{}{"token": token, "enabled": true}
	where := map[string]interface{}{"id": userId}
	this.GetModel("users").Update(this.isAdmin(), userId, params, where)

	utils.SendJSReply(map[string]interface{}{"result": "Письмо отправлено"}, this.Response)
}
func (this *RegistrationController) Login() {
	data, err := utils.ParseJS(this.Request, this.Response)
	if utils.HandleErr("[RegistrationController::Login]: ", err, this.Response) {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)

		return
	}

	login := data["login"].(string)
	pass := data["password"].(string)

	var id int
	var enabled bool
	var passHash, salt string
	result := make(map[string]interface{}, 1)

	if err = this.GetModel("users").
		LoadWherePart(map[string]interface{}{"login": login}).
		SelectRow([]string{"id", "pass", "salt", "enabled"}).
		Scan(&id, &passHash, &salt, &enabled); err != nil {
		result["result"] = "invalidCredentials"

	} else if enabled == false {
		result["result"] = "notEnabled"

	} else if passHash != utils.GetMD5Hash(pass+salt) {
		result["result"] = "badPassword"

	} else {
		result["result"] = "ok"

		sid := utils.GetRandSeq(HASH_SIZE)
		params := map[string]interface{}{"sid": sid, "enabled": true}
		where := map[string]interface{}{"id": id}
		this.GetModel("users").Update(this.isAdmin(), id, params, where)
		sessions.SetSession(this.Response, map[string]interface{}{"sid": sid})
	}

	utils.SendJSReply(result, this.Response)
}
Example #5
0
func WellcomeToProfile(w http.ResponseWriter, r *http.Request) {
	newContreoller := new(BaseController).Handler()

	parts := strings.Split(r.URL.Path, "/")
	token := parts[len(parts)-1]

	var id int
	err := newContreoller.GetModel("users").
		LoadWherePart(map[string]interface{}{"token": token}).
		SelectRow([]string{"id"}).
		Scan(&id)
	if utils.HandleErr("[WellcomeToProfile]: ", err, w) || id == 0 {
		return
	}

	sid := utils.GetRandSeq(HASH_SIZE)
	params := map[string]interface{}{"sid": sid, "enabled": true}
	where := map[string]interface{}{"id": id}
	newContreoller.GetModel("users").Update(false, -1, params, where)
	sessions.SetSession(w, map[string]interface{}{"sid": sid})
	http.Redirect(w, r, "/usercontroller/showcabinet", 200)
}
Example #6
0
func (this *PersonsModel) Add(userId int, params map[string]interface{}) error {
	var to, address string

	token := utils.GetRandSeq(HASH_SIZE)
	params["token"] = token

	log.Println("face_id: ", params["face_id"])
	log.Println("group_id: ", params["group_id"])
	log.Println("status: ", params["status"])

	if db.IsExists("persons", []string{"face_id", "group_id"}, []interface{}{params["face_id"], params["group_id"]}) {
		return errors.New("Участник уже состоит в группе")
	}

	query := `SELECT param_values.value
        FROM param_values
        INNER JOIN registrations ON registrations.id = param_values.reg_id
        INNER JOIN params ON params.id = param_values.param_id
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE params.id in (5, 6, 7) AND users.id = $1 AND events.id = 1 ORDER BY params.id;`
	data := db.Query(query, []interface{}{userId})
	headName := ""
	if len(data) < 3 {
		return errors.New("Данные о руководителе группы отсутсвуют")

	} else {
		headName = data[0].(map[string]interface{})["value"].(string)
		headName += " " + data[1].(map[string]interface{})["value"].(string)
		headName += " " + data[2].(map[string]interface{})["value"].(string)
	}

	groupId, err := strconv.Atoi(params["group_id"].(string))
	if err != nil {
		return err
	}

	var groupName string
	db.QueryRow("SELECT name FROM groups WHERE id = $1;", []interface{}{groupId}).Scan(&groupName)

	query = `SELECT param_values.value
        FROM param_values
        INNER JOIN registrations ON registrations.id = param_values.reg_id
        INNER JOIN params ON params.id = param_values.param_id
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE params.id in (4, 5, 6, 7) AND faces.id = $1 AND events.id = 1 ORDER BY params.id;`
	data = db.Query(query, []interface{}{params["face_id"]})
	if len(data) < 4 {
		return errors.New("Данные о приглашаемом участнике отсутсвуют.")

	} else {
		address = data[0].(map[string]interface{})["value"].(string)
		to = data[1].(map[string]interface{})["value"].(string)
		to += " " + data[2].(map[string]interface{})["value"].(string)
		to += " " + data[3].(map[string]interface{})["value"].(string)
	}

	if !mailer.InviteToGroup(to, address, token, headName, groupName) {
		return errors.New("Участник скорее всего указал неправильный email, отправить письмо-приглашенине невозможно")
	}

	this.LoadModelData(params).QueryInsert("").Scan()
	return nil
}
Example #7
0
func (this *GroupController) AddPerson() {
	userId, err := this.CheckSid()
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response)
		return
	}

	request, err := utils.ParseJS(this.Request, this.Response)
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	groupId, err := strconv.Atoi(request["group_id"].(string))
	if err != nil {
		utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response)
		return
	}

	var groupName string
	db.QueryRow("SELECT name FROM groups WHERE id = $1;", []interface{}{groupId}).Scan(&groupName)

	date := time.Now().Format("2006-01-02T15:04:05Z00:00")
	token := utils.GetRandSeq(HASH_SIZE)
	to, address, headName := "", "", ""

	query := `SELECT param_values.value
        FROM param_values
        INNER JOIN registrations ON registrations.id = param_values.reg_id
        INNER JOIN params ON params.id = param_values.param_id
        INNER JOIN events ON events.id = registrations.event_id
        INNER JOIN faces ON faces.id = registrations.face_id
        INNER JOIN users ON users.id = faces.user_id
        WHERE params.id in (5, 6, 7) AND users.id = $1 AND events.id = 1 ORDER BY params.id;`
	data := db.Query(query, []interface{}{userId})

	if len(data) < 3 {
		utils.SendJSReply(map[string]interface{}{"result": "Данные о руководителе группы отсутсвуют"}, this.Response)
		return

	} else {
		headName = data[0].(map[string]interface{})["value"].(string)
		headName += " " + data[1].(map[string]interface{})["value"].(string)
		headName += " " + data[2].(map[string]interface{})["value"].(string)
	}

	var faceId int
	this.GetModel("faces").QueryInsert("RETURNING id").Scan(&faceId)

	this.GetModel("persons").
		LoadModelData(map[string]interface{}{"face_id": faceId, "group_id": groupId, "status": false, "token": token}).
		QueryInsert("").
		Scan()

	var regId int
	this.GetModel("registrations").
		LoadModelData(map[string]interface{}{"face_id": faceId, "event_id": 1, "status": false}).
		QueryInsert("RETURNING id").
		Scan(&regId)

	var paramValueIds []string

	for _, element := range request["data"].([]interface{}) {
		paramId, err := strconv.Atoi(element.(map[string]interface{})["id"].(string))
		if err != nil {
			log.Println(err.Error())
			continue
		}

		query := `SELECT params.name FROM params WHERE params.id = $1;`
		res := db.Query(query, []interface{}{paramId})

		name := res[0].(map[string]interface{})["name"].(string)
		value := element.(map[string]interface{})["value"].(string)

		if utils.MatchRegexp("^[ \t\v\r\n\f]{0,}$", value) {
			db.QueryDeleteByIds("param_vals", strings.Join(paramValueIds, ", "))
			db.QueryDeleteByIds("registrations", strconv.Itoa(regId))
			db.QueryDeleteByIds("faces", strconv.Itoa(faceId))
			utils.SendJSReply(map[string]interface{}{"result": "Заполните параметр '" + name + "'."}, this.Response)
			return
		}

		var paramValId int
		paramValues := this.GetModel("param_values")
		err = paramValues.LoadModelData(map[string]interface{}{
			"param_id": paramId,
			"value":    value,
			"date":     date,
			"user_id":  userId,
			"reg_id":   regId}).
			QueryInsert("RETURNING id").
			Scan(&paramValId)
		if err, ok := err.(*pq.Error); ok {
			log.Println(err.Code.Name())
		}

		paramValueIds = append(paramValueIds, strconv.Itoa(paramValId))

		if paramId == 4 {
			address = value
		} else if paramId == 5 || paramId == 6 || paramId == 7 {
			to += value + " "
		}
	}

	if !mailer.InviteToGroup(to, address, token, headName, groupName) {
		utils.SendJSReply(
			map[string]interface{}{
				"result": "Вы указали неправильный email, отправить письмо-приглашенине невозможно"},
			this.Response)
		return
	}

	utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response)
}