func Exec(query string, params []interface{}) sql.Result { log.Println(query) stmt, err := DB.Prepare(query) utils.HandleErr("[queries.Exec] Prepare: ", err, nil) defer stmt.Close() result, err := stmt.Exec(params...) utils.HandleErr("[queries.Exec] Exec: ", err, nil) return result }
func QueryRow(query string, params []interface{}) *sql.Row { log.Println(query) stmt, err := DB.Prepare(query) utils.HandleErr("[queries.QueryRow] Prepare: ", err, nil) defer stmt.Close() result := stmt.QueryRow(params...) utils.HandleErr("[queries.QueryRow] Query: ", err, nil) return result }
func (this *GridController) GetSubTable() { userId, err := this.CheckSid() if err != nil { http.Error(this.Response, "Unauthorized", 400) return } request, err := utils.ParseJS(this.Request, this.Response) if err != nil { http.Error(this.Response, err.Error(), 400) return } model := this.GetModel(request["table"].(string)) index, _ := strconv.Atoi(request["index"].(string)) subModel := this.GetModel(model.GetSubTable(index)) subModel.LoadWherePart(map[string]interface{}{model.GetSubField(): request["id"]}) response, err := json.Marshal(map[string]interface{}{ "name": subModel.GetTableName(), "caption": subModel.GetCaption(), "colnames": subModel.GetColNames(), "columns": subModel.GetColumns(), "colmodel": subModel.GetColModel(this.isAdmin(), userId)}) if utils.HandleErr("[GridController::GetSubTable] Marshal: ", err, this.Response) { return } fmt.Fprintf(this.Response, "%s", string(response)) }
func (this *RegistrationController) Logout() { userId, err := this.CheckSid() if err != nil { http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized) utils.SendJSReply(map[string]string{"result": "badSid"}, this.Response) return } var enabled bool if err = this.GetModel("users"). LoadWherePart(map[string]interface{}{"id": userId}). SelectRow([]string{"enabled"}). Scan(&enabled); utils.HandleErr("[RegistrationController::Logout]: ", err, this.Response) { utils.SendJSReply(map[string]string{"result": err.Error()}, this.Response) return } params := map[string]interface{}{"enabled": enabled, "sid": " "} where := map[string]interface{}{"id": userId} this.GetModel("users").Update(this.isAdmin(), userId, params, where) sessions.ClearSession(this.Response) utils.SendJSReply(map[string]string{"result": "ok"}, this.Response) }
//----------------------------------------------------------------------------- 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 ConvertData(columns []string, size int64, rows *sql.Rows) []interface{} { row := make([]interface{}, len(columns)) values := make([]interface{}, len(columns)) answer := make([]interface{}, size) for i, _ := range row { row[i] = &values[i] } j := 0 for rows.Next() { rows.Scan(row...) record := make(map[string]interface{}, len(values)) for i, col := range values { if col != nil { //fmt.Printf("\n%s: type= %s\n", columns[i], reflect.TypeOf(col)) switch col.(type) { case bool: record[columns[i]] = col.(bool) break case int: record[columns[i]] = col.(int) break case int64: record[columns[i]] = int(col.(int64)) break case float64: record[columns[i]] = col.(float64) break case string: record[columns[i]] = col.(string) break // case []byte: // record[columns[i]] = string(col.([]byte)) // break case []int8: record[columns[i]] = col.([]string) break case time.Time: record[columns[i]] = col break case []uint8: data := strings.Split(strings.Trim(string(col.([]uint8)), "{}"), ",") if len(data) == 1 { record[columns[i]] = data[0] } else { record[columns[i]] = data } break default: utils.HandleErr("ConvertData: ", errors.New("Unexpected type."), nil) } } answer[j] = record } j++ } rows.Close() return answer }
func Query(query string, params []interface{}) []interface{} { log.Println(query) stmt, err := DB.Prepare(query) utils.HandleErr("[queries.Query] Prepare: ", err, nil) defer stmt.Close() rows, err := stmt.Query(params...) utils.HandleErr("[queries.Query] Query: ", err, nil) defer rows.Close() rowsInf := Exec(query, params) columns, err := rows.Columns() utils.HandleErr("[queries.Query] Columns: ", err, nil) size, err := rowsInf.RowsAffected() utils.HandleErr("[queries.Query] RowsAffected: ", err, nil) return ConvertData(columns, size, rows) }
func loadUsers() { base := new(controllers.BaseController) date := time.Now().Format("2006-01-02T15:04:05Z00:00") for i := 0; i < USER_COUNT; i++ { rand.Seed(int64(i)) userName := "******" + strconv.Itoa(i) userEmail := userName + "@mail.ru" result, regId := base.RegistrationController().Register(userName, "secret"+strconv.Itoa(i), userEmail, "user") if result != "ok" { utils.HandleErr("[loadUsers]: "+result, nil, nil) continue } query := `INSERT INTO param_values (param_id, value, date, user_id, reg_id) VALUES (4, $1, $2, NULL, $3);` db.Exec(query, []interface{}{userEmail, date, regId}) for k := 5; k < 8; k++ { query := `INSERT INTO param_values (param_id, value, date, user_id, reg_id) VALUES (` + strconv.Itoa(k) + `, '` + userName + `', $1, NULL, $2);` db.Exec(query, []interface{}{date, regId}) } query = `SELECT users.token FROM registrations INNER JOIN events ON registrations.event_id = events.id INNER JOIN faces ON faces.id = registrations.face_id INNER JOIN users ON users.id = faces.user_id WHERE events.id = $1 AND registrations.id = $2;` res := db.Query(query, []interface{}{1, regId}) if len(res) == 0 { utils.HandleErr("[loadUsers]: ", errors.New("Data are not faund."), nil) continue } token := res[0].(map[string]interface{})["token"].(string) base.RegistrationController().ConfirmUser(token) } }
func (this *GridController) EditGridRow(tableName string) { userId, err := this.CheckSid() if err != nil { http.Redirect(this.Response, this.Request, "", http.StatusUnauthorized) return } model := this.GetModel(tableName) if model == nil { utils.HandleErr("[GridController::Edit] GetModel: ", errors.New("Unexpected table name"), this.Response) http.Error(this.Response, "Unexpected table name", 400) return } params := make(map[string]interface{}, len(model.GetColumns())) for i := 0; i < len(model.GetColumns()); i++ { params[model.GetColumnByIdx(i)] = this.Request.PostFormValue(model.GetColumnByIdx(i)) } switch this.Request.PostFormValue("oper") { case "edit": rowId, err := strconv.Atoi(this.Request.PostFormValue("id")) if err != nil { http.Error(this.Response, err.Error(), 400) return } model.Update(this.isAdmin(), userId, params, map[string]interface{}{"id": rowId}) break case "add": err := model.Add(userId, params) if err != nil { http.Error(this.Response, err.Error(), 400) } break case "del": for _, v := range strings.Split(this.Request.PostFormValue("id"), ",") { id, err := strconv.Atoi(v) if err != nil { http.Error(this.Response, err.Error(), 400) return } model.Delete(id) } break } }
func SendEmail(address, tmp string, context *SmtpTemplateData) bool { var doc bytes.Buffer template.Must(template.New("email").Parse(tmp)).Execute(&doc, context) err = smtp.SendMail( Admin_.SMTPServer+":"+Admin_.Port, auth, Admin_.Email, []string{address}, doc.Bytes()) return !utils.HandleErr("[SendEmail] Error attempting to send a mail: ", err, nil) }
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 loadAdmin() { base := new(controllers.BaseController) date := time.Now().Format("2006-01-02T15:04:05Z00:00") result, regId := base.RegistrationController().Register("admin", "password", mailer.Admin_.Email, "admin") if result != "ok" { utils.HandleErr("[LoadAdmin]: "+result, nil, nil) return } query := `INSERT INTO param_values (param_id, value, date, user_id, reg_id) VALUES (4, $1, $2, NULL, $3);` db.Exec(query, []interface{}{mailer.Admin_.Email, date, regId}) for k := 5; k < 8; k++ { query := `INSERT INTO param_values (param_id, value, date, user_id, reg_id) VALUES (` + strconv.Itoa(k) + `, 'admin', $1, NULL, $2);` db.Exec(query, []interface{}{date, regId}) } query = `SELECT users.token FROM registrations INNER JOIN events ON registrations.event_id = events.id INNER JOIN faces ON faces.id = registrations.face_id INNER JOIN users ON users.id = faces.user_id WHERE events.id = $1 AND registrations.id = $2;` res := db.Query(query, []interface{}{1, regId}) if len(res) == 0 { utils.HandleErr("[LoadAdmin]: ", errors.New("Data are not faund."), nil) return } token := res[0].(map[string]interface{})["token"].(string) base.RegistrationController().ConfirmUser(token) }
func (this *BlankController) GetBlankByEventId(id string) { eventId, err := strconv.Atoi(id) if utils.HandleErr("[BlankController::GetBlankByEventId] event_id Atoi: ", err, this.Response) { return } if !sessions.CheckSession(this.Response, this.Request) && eventId != 1 { this.Render([]string{"mvc/views/loginpage.html", "mvc/views/login.html"}, "loginpage", nil) return } this.Render( []string{"mvc/views/item.html"}, "item", map[string]interface{}{"data": new(models.BlankManager).NewPersonalBlank(true).GetEmptyBlank(eventId)}) }
func (this *UserController) ResetPassword() { userId, err := this.CheckSid() if err != nil { http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized) return } request, err := utils.ParseJS(this.Request, this.Response) if err != nil { utils.SendJSReply(err.Error(), this.Response) return } pass := request["pass"].(string) if !utils.MatchRegexp("^.{6,36}$", pass) { utils.SendJSReply(map[string]interface{}{"result": "badPassword"}, this.Response) return } var id int if request["id"] == nil { id = userId } else { id, err = strconv.Atoi(request["id"].(string)) if utils.HandleErr("[UserController::ResetPassword] strconv.Atoi: ", err, this.Response) { utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response) return } } var enabled bool salt := strconv.Itoa(int(time.Now().Unix())) where := map[string]interface{}{"id": id} user := this.GetModel("users") user.LoadWherePart(where). SelectRow([]string{"enabled"}). Scan(&enabled) params := map[string]interface{}{"enabled": enabled, "salt": salt, "pass": utils.GetMD5Hash(pass + salt)} user.Update(this.isAdmin(), id, params, where) utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response) }
func (this *RegistrationController) RejectUser(token string) { var userId int err := this.GetModel("users"). LoadWherePart(map[string]interface{}{"token": token}). SelectRow([]string{"id"}). Scan(&userId) if utils.HandleErr("[RegistrationController::RejectUser]: ", err, this.Response) { if this.Response != nil { this.Render([]string{"mvc/views/msg.html"}, "msg", err.Error()) } return } db.QueryDeleteByIds("users", strconv.Itoa(userId)) if this.Response != nil { this.Render([]string{"mvc/views/msg.html"}, "msg", "Вы успешно отписаны от рассылок Secret Oasis.") } }
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) }
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) }
func (this *RegistrationController) ConfirmUser(token string) { var userId int err := this.GetModel("users"). LoadWherePart(map[string]interface{}{"token": token}). SelectRow([]string{"id"}). Scan(&userId) if utils.HandleErr("[RegistrationController::ConfirmUser]: ", err, this.Response) { if this.Response != nil { this.Render([]string{"mvc/views/msg.html"}, "msg", err.Error()) } return } params := map[string]interface{}{"enabled": true, "token": " "} where := map[string]interface{}{"id": userId} this.GetModel("users").Update(this.isAdmin(), userId, params, where) if this.Response != nil { this.Render([]string{"mvc/views/msg.html"}, "msg", "Регистрация подтверждена.") } }
func (this *IndexController) LoadContestsFromCats() { url := "http://imcs.dvfu.ru/cats/main.pl?f=contests;filter=unfinished;json=1" result, err := http.Get(url) if utils.HandleErr("[loadContestsFromCats] http.Get(url): ", err, this.Response) { return } defer result.Body.Close() body, err := ioutil.ReadAll(result.Body) if utils.HandleErr("[loadContestsFromCats] ioutil.ReadAll(data.Body): ", err, this.Response) { return } var data map[string]interface{} err = json.Unmarshal(body, &data) if utils.HandleErr("[loadContestsFromCats] json.Unmarshal(body, &data): ", err, this.Response) { return } for _, v := range data["contests"].([]interface{}) { contest := v.(map[string]interface{}) time_, err := time.Parse("20060102T150405", contest["start_time"].(string)) if utils.HandleErr("[loadContestsFromCats] time.Parse: ", err, this.Response) { continue } startDate, err := time.Parse("02.01.2006 15:04", contest["start_date"].(string)) if utils.HandleErr("[loadContestsFromCats] time.Parse: ", err, this.Response) { continue } finishDate, err := time.Parse("02.01.2006 15:04", contest["finish_date"].(string)) if utils.HandleErr("[loadContestsFromCats] time.Parse: ", err, this.Response) { continue } this.GetModel("events"). LoadModelData(map[string]interface{}{ "name": contest["name"], "date_start": startDate.Format("2006-01-02 15:04:05"), "date_finish": finishDate.Format("2006-01-02 15:04:05"), "time": time_.Format("15:04:05"), "url": "http://imcs.dvfu.ru/cats/main.pl?f=contests;cid=" + strconv.Itoa(int(contest["id"].(float64))), }). QueryInsert(""). Scan() } }
func (this *UserController) CheckEnable(id string) { eventId, err := strconv.Atoi(id) if utils.HandleErr("[UserController::CheckEnable] event_id Atoi: ", err, this.Response) { utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response) return } if eventId == 1 { if sessions.CheckSession(this.Response, this.Request) { utils.SendJSReply(map[string]interface{}{"result": "authorized"}, this.Response) return } utils.SendJSReply(map[string]interface{}{"result": "ok"}, this.Response) return } userId, err := this.CheckSid() if err != nil && eventId != 1 { utils.SendJSReply(map[string]interface{}{"result": "Unauthorized"}, this.Response) return } regId := this.regExists(userId, eventId) if regId == -1 { groups := this.GetModel("groups") persons := this.GetModel("persons") groupsModel := Model{ TableName: groups.GetTableName(), ColNames: groups.GetColNames(), ColModel: groups.GetColModel(false, userId), Caption: groups.GetCaption(), Sub: groups.GetSub(), SubTableName: persons.GetTableName(), SubCaption: persons.GetCaption(), SubColModel: persons.GetColModel(false, userId), SubColNames: persons.GetColNames()} utils.SendJSReply(map[string]interface{}{"result": "ok", "groups": groupsModel}, this.Response) } else { var teamEvent bool if err = this.GetModel("events"). LoadWherePart(map[string]interface{}{"id": eventId}). SelectRow([]string{"team"}). Scan(&teamEvent); err != nil { utils.SendJSReply(map[string]interface{}{"result": err.Error()}, this.Response) return } if teamEvent { var groupRegId int query := `SELECT group_registrations.id FROM regs_groupregs INNER JOIN registrations ON registrations.id = regs_groupregs.reg_id INNER JOIN group_registrations ON group_registrations.id = regs_groupregs.groupreg_id INNER JOIN events ON events.id = registrations.event_id AND events.id = group_registrations.event_id INNER JOIN faces ON faces.id = registrations.face_id INNER JOIN users ON users.id = faces.user_id INNER JOIN groups ON group_registrations.group_id = groups.id WHERE users.id = $1 AND events.id = $2 GROUP BY group_registrations.id;` db.QueryRow(query, []interface{}{userId, eventId}).Scan(&groupRegId) utils.SendJSReply(map[string]interface{}{"result": "regExists", "groupRegId": strconv.Itoa(groupRegId)}, this.Response) } else { utils.SendJSReply(map[string]interface{}{"result": "regExists", "regId": strconv.Itoa(regId)}, this.Response) } } }
func (this *UserController) ShowCabinet() { userId, err := this.CheckSid() if err != nil { http.Redirect(this.Response, this.Request, "/", http.StatusUnauthorized) return } var role string if err = this.GetModel("users"). LoadWherePart(map[string]interface{}{"id": userId}). SelectRow([]string{"role"}). Scan(&role); err != nil { utils.HandleErr("[UserController::ShowCabinet]: ", err, this.Response) return } if role == "admin" { model := Model{Columns: db.Tables, ColNames: db.TableNames} this.Render([]string{"mvc/views/" + role + ".html"}, role, model) } else { groups := this.GetModel("groups") persons := this.GetModel("persons") groupsModel := Model{ TableName: groups.GetTableName(), ColNames: groups.GetColNames(), ColModel: groups.GetColModel(false, userId), Caption: groups.GetCaption(), Sub: groups.GetSub(), SubTableName: persons.GetTableName(), SubCaption: persons.GetCaption(), SubColModel: persons.GetColModel(false, userId), SubColNames: persons.GetColNames()} regs := this.GetModel("registrations") regsModel := Model{ TableName: regs.GetTableName(), ColNames: regs.GetColNames(), ColModel: regs.GetColModel(false, userId), Caption: regs.GetCaption()} groupRegs := this.GetModel("group_registrations") groupRegsModel := Model{ TableName: groupRegs.GetTableName(), ColNames: groupRegs.GetColNames(), ColModel: groupRegs.GetColModel(false, userId), Caption: groupRegs.GetCaption(), Sub: groupRegs.GetSub(), SubTableName: persons.GetTableName(), SubCaption: persons.GetCaption(), SubColModel: persons.GetColModel(false, userId), SubColNames: persons.GetColNames()} query := `SELECT params.name, param_values.value, users.login 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 = 4 AND users.id = $1;` data := db.Query(query, []interface{}{userId}) faces := this.GetModel("faces") facesModel := Model{ ColModel: faces.GetColModel(false, userId), TableName: faces.GetTableName(), ColNames: faces.GetColNames(), Caption: faces.GetCaption()} params := this.GetModel("param_values") paramsModel := Model{ ColModel: params.GetColModel(false, userId), TableName: params.GetTableName(), ColNames: params.GetColNames(), Caption: params.GetCaption()} events := this.GetModel("events") eventsModel := Model{ ColModel: events.GetColModel(false, userId), TableName: events.GetTableName(), ColNames: events.GetColNames(), Caption: events.GetCaption()} this.Render( []string{"mvc/views/" + role + ".html"}, role, map[string]interface{}{ "group": groupsModel, "reg": regsModel, "groupreg": groupRegsModel, "faces": facesModel, "params": paramsModel, "events": eventsModel, "userData": data}) } }