// StartConnector starts up the websocket connector of the bee server // config settings from config file // commandChan channel to send commands to the controller // doneChan channel to signal end or get it signaled func StartWebsockets(doneChan chan bool) { address := beego.AppConfig.String("httpaddr") dir := beego.AppConfig.String("websockets::dir") port := beego.AppConfig.String("websockets::port") beego.Trace("dir:", dir, "address:", address, "port:", port) http.Handle(dir, websocket.Handler(func(ws *websocket.Conn) { beego.Trace("New socket connection started ...") s := socket{ws, make(chan bool)} go translateMessages(s) encoder := json.NewEncoder(s) data := Data{ "Time": time.Now().UnixNano() / int64(time.Millisecond), } encoder.Encode(&data) <-s.done beego.Trace("Socket connection gone ...") })) beego.Trace("--- Spielplatz connector started on ", address+":"+port, ". Listening ...") err := http.ListenAndServe(address+":"+port, nil) if err != nil { beego.Error(err) doneChan <- true } }
func init() { // Initialized recent viewed project list. num, err := beego.AppConfig.Int("recentViewedProNum") if err == nil { recentViewedProNum = num beego.Trace("Loaded 'recentViewedProNum' -> value:", recentViewedProNum) } else { beego.Trace("Failed to load 'recentViewedProNum' -> Use default value:", recentViewedProNum) } recentViewedPros = make([]*recentPro, 0, recentViewedProNum) // Get recent viewed projects from database. proinfos, _ := models.GetRecentPros(recentViewedProNum) for _, p := range proinfos { // Only projects with import path length is less than 40 letters will be showed. if len(p.Path) < 40 { recentViewedPros = append(recentViewedPros, &recentPro{ Path: p.Path, Synopsis: p.Synopsis, ViewedTime: p.ViewedTime, IsGoRepo: p.ProName == "Go" && strings.Index(p.Path, ".") == -1, }) } } // Initialize project tags. labelList = strings.Split(beego.AppConfig.String("labels"), "|") for _, s := range labelList { labelSet += """ + s + ""," } labelSet = labelSet[:len(labelSet)-1] }
func (this *TextMessageController) Post() { r := this.Ctx.Request //this.ParseForm() r.ParseForm() //beego.Trace("ToUserName", this.GetString("ToUserName")) //beego.Trace("ToUserName", r.PostFormValue("ToUserName")) //beego.Trace("MsgType", this.GetString("MsgType")) //beego.Trace("MsgType", r.PostFormValue("MsgType")) for k, v := range r.Form { beego.Trace("key:", k) beego.Trace("val:", strings.Join(v, "")) } //for k, v := range r.PostForm { // beego.Trace("key:", k) // beego.Trace("val:", strings.Join(v, "")) //} //for i, s := range string(this.Ctx.Input.RequestBody) { // beego.Trace(i, ":", s, ":", string(s)) //} //beego.Trace("body:", string(this.Ctx.Input.RequestBody)) output, _ := iconv.ConvertString(string(this.Ctx.Input.RequestBody), "utf8", "gbk") //beego.Trace(charmap.Windows1252.NewEncoder()) //encoding.UTF8Validator.Transform() beego.Trace(output) this.Data["Out"] = "sdfasdfasdfasdfasdfa" this.TplNames = "out.tpl" }
func init() { // Initialized recent viewed project list. num, err := beego.AppConfig.Int("recentViewedProNum") if err == nil { recentViewedProNum = num beego.Trace("Loaded 'recentViewedProNum' -> value:", recentViewedProNum) } else { beego.Trace("Failed to load 'recentViewedProNum' -> Use default value:", recentViewedProNum) } recentViewedPros = make([]*recentPro, 0, recentViewedProNum) // Get recent viewed projects from database. proinfos, _ := models.GetRecentPros(recentViewedProNum) for _, p := range proinfos { recentViewedPros = append(recentViewedPros, &recentPro{ Path: p.Path, ViewedTime: p.ViewedTime, IsGoRepo: p.ProName == "Go", Views: p.Views, }) } // Initialized language type list. langs := strings.Split(beego.AppConfig.String("language"), "|") names := strings.Split(beego.AppConfig.String("langNames"), "|") langTypes = make([]*langType, 0, len(langs)) for i, v := range langs { langTypes = append(langTypes, &langType{ Lang: v, Name: names[i], }) } }
func (this *AuthController) DoLogin() { this.CheckRequestFrequency(3, 15, 30) if this.IsLogin { this.Redirect("/", 302) } valid := validation.Validation{} form := LoginForm{} if err := this.ParseForm(&form); err != nil { beego.Error(err) } b, err := valid.Valid(form) if err != nil { beego.Error(err) } if !b { this.loginPageWithErrors(form, valid.Errors) return } //用户不存在? user := models.User{Username: form.Username, Email: form.Username} if err := user.Read("Username"); err != nil { if err2 := user.Read("Email"); err2 != nil { errMsg := fmt.Sprintf("用户 %s 不存在!", form.Username) beego.Trace(errMsg) valid.SetError("username", errMsg) this.loginPageWithErrors(form, valid.Errors) return } } //用户被禁止? if user.IsBanned { beego.Trace(fmt.Sprintf("用户%s被禁用,不能登录!", user.Username)) valid.SetError("username", "抱歉,您被禁止登录!") this.loginPageWithErrors(form, valid.Errors) return } //检查密码 if !user.VerifyPassword(form.Password) { beego.Trace(fmt.Sprintf("%s 登录失败!", form.Username)) valid.SetError("password", "密码错误") this.loginPageWithErrors(form, valid.Errors) return } //验证全部通过 var remember bool if form.Remember != "" { remember = true } this.LogUserIn(&user, remember) this.Redirect(GetLoginRedirectUrl(this.Ctx), 302) return }
func (c *MainController) Get() { // c.Data["Website"] = "beego.me" // c.Data["Email"] = "*****@*****.**" // c.TplName = "index.tpl" c.Ctx.WriteString("appname: " + beego.AppConfig.String("appname") + "\nhttpport: " + beego.AppConfig.String("httpport") + "\nrunmode: " + beego.AppConfig.String("runmode")) beego.Trace("trace 1") beego.Info("info 1") beego.SetLevel(beego.LevelInformational) beego.Trace("trace 2") beego.Info("info 2") }
func DefaultData() { o := orm.NewOrm() var configure Configure configure.CName = "status" configure.CValue = "0" //0未启动,1启动,2已押注 _, err := o.Insert(&configure) if err != nil { beego.Error(err) } else { beego.Trace("初始化status……") } configure.CName = "prize" configure.CValue = "" _, err = o.Insert(&configure) if err != nil { beego.Error(err) } else { beego.Trace("初始化prize……") } configure.CName = "prize_url" configure.CValue = "http://yun.baozoumanhua.com/Project/RageMaker0/images/0/5.png" _, err = o.Insert(&configure) if err != nil { beego.Error(err) } else { beego.Trace("初始化prize_url……") } // 初始化赛马信息 horse := []Horse{ {Name: "Oe", Win: 0, Lose: 0}, {Name: "To", Win: 0, Lose: 0}, {Name: "Tr", Win: 0, Lose: 0}, {Name: "Fr", Win: 0, Lose: 0}, {Name: "Fe", Win: 0, Lose: 0}, {Name: "Sx", Win: 0, Lose: 0}, } successNums, err := o.InsertMulti(1, horse) if err != nil { beego.Error(err) } else { beego.Trace("初始化" + strconv.FormatInt(successNums, 10) + "匹马……") } }
func (this *SocialAuthController) processLoginForm(socialType social.SocialType) { valid := validation.Validation{} form := SocialAuthLoginForm{} var user models.User if err := this.ParseForm(&form); err != nil { beego.Error(err) } b, err := valid.Valid(form) if err != nil { beego.Error(err) } if !b { goto showLoginErrors } //用户不存在? user = models.User{Username: form.Username, Email: form.Username} if err := user.Read("Username"); err != nil { if err2 := user.Read("Email"); err2 != nil { errMsg := fmt.Sprintf("用户 %s 不存在!", form.Username) valid.SetError("Username", errMsg) goto showLoginErrors } } //用户被禁止? if user.IsBanned { beego.Trace(fmt.Sprintf("用户%s被禁用,不能登录!", user.Username)) valid.SetError("Username", "抱歉,您被禁止登录!") goto showLoginErrors } //检查密码 if !user.VerifyPassword(form.Password) { beego.Trace(fmt.Sprintf("%s 登录失败!", form.Username)) valid.SetError("Password", "密码错误") goto showLoginErrors } //验证全部通过 if loginRedirect, _, err := SocialAuth.ConnectAndLogin(this.Ctx, socialType, user.Id); err != nil { beego.Error("ConnectAndLogin:"******"Let's redirect ", loginRedirect) this.Redirect(loginRedirect, 302) return } showLoginErrors: this.Data["LoginForm"] = form this.Data["LoginFormErrors"] = valid.Errors return }
func Test_AuthController_Auth_Success(t *testing.T) { b, _ := json.Marshal(&mocked_auth_info) r, _ := http.NewRequest("POST", "/api/auth", bytes.NewBuffer(b)) w := httptest.NewRecorder() beego.BeeApp.Handlers.ServeHTTP(w, r) beego.Trace("testing", "Test_AuthController_Auth_Success", "Code[%d]\n%s", w.Code, w.Body.String()) Convey("Subject: Test Auth Success Endpoint\n", t, func() { Convey("Status code should be 200", func() { So(w.Code, ShouldEqual, 200) }) Convey("The result should not be empty", func() { So(w.Body.Len(), ShouldBeGreaterThan, 0) }) Convey("The result should be an true Success", func() { type Success struct { Succ bool `json:"success"` } var result Success json.Unmarshal(w.Body.Bytes(), &result) So(result == Success{true}, ShouldBeTrue) }) Convey("The response should set session", func() { So(strings.Contains(w.HeaderMap.Get( http.CanonicalHeaderKey("Set-Cookie")), "beegosessionID"), ShouldBeTrue) }) }) }
func (this *ImportController) Post() { //check islogin session := this.GetSession("Admin") if session == nil { beego.Trace("session verify failed!") this.Redirect("/", 302) return } saveFileName := "temp" + strconv.FormatInt(int64(time.Now().UnixNano()), 10) + ".xlsx" beego.Debug("saveFileName=", saveFileName) this.SaveToFile("file", saveFileName) devices := make([]models.Deviceinfo, 0) xlFile, err := xlsx.OpenFile(saveFileName) if err != nil { beego.Error("Open excel file!", err) } for _, sheet := range xlFile.Sheets { for _, row := range sheet.Rows { for _, cell := range row.Cells { device := models.Deviceinfo{ Mac: cell.String(), ImportTime: time.Now(), InvalidTime: time.Now().Add(3 * 30 * 24 * time.Hour), } //check mac address format if !CheckMacFormat(device.Mac) { beego.Info(device.Mac, "not a mac address!") continue } //if the mac address had existed,skip it if models.ImportDeviceCheck(&device) { beego.Info(device.Mac, "had been imported!") continue } devices = append(devices, device) } } } //delete used file err = os.Remove(saveFileName) if err != nil { beego.Error("Remove temp excel file failed!", err) } ok := models.ImportDevices(&devices) if ok { beego.Info("ImportDevices success!") this.Redirect("/home", 301) this.Data["IsImported"] = true return } else { beego.Info("ImportDevices failed! once again") this.Redirect("/import", 302) return } }
func (this *CommandController) Post() { //检查登录状态 session := this.GetSession("Admin") if session == nil { beego.Trace("session verify failed!") this.Redirect("/", 302) return } //获取表单信息 mac := this.Input().Get("mac") beego.Debug("mac=", mac) commandContent := this.Input().Get("commandContent") beego.Debug("commandContent=", commandContent) //下发action device := models.Deviceinfo{ Mac: mac, Act: commandContent, } ok := models.SetAct(&device) if !ok { beego.Info("set action failed!") } //返回设备页面 this.Redirect("/home", 302) return }
func (this *BaseController) Prepare() { //Accept-Language acceptLanguage := this.Ctx.Request.Header.Get("Accept-Language") if len(acceptLanguage) > 4 { acceptLanguage = acceptLanguage[:5] // Only compare first 5 letters. if i18n.IsExist(acceptLanguage) { Lang = acceptLanguage } } if len(Lang) == 0 { Lang = "en-US" } // Initialized language type list. langs := strings.Split(beego.AppConfig.String("lang::types"), "|") names := strings.Split(beego.AppConfig.String("lang::names"), "|") langTypes := make([]*langType, 0, len(langs)) for i, v := range langs { langTypes = append(langTypes, &langType{ Lang: v, Name: names[i], }) } for _, lang := range langs { beego.Trace("Loading language: " + lang) if err := i18n.SetMessage(lang, "lang/"+"locale_"+lang+".ini"); err != nil { beego.Error("Fail to set message file: " + err.Error()) return } } }
///////////////////////////////////////////////////////////// // MountResourceFiles func MountResourceFiles(user string, project string) error { resources := []string{"image", "sound"} for _, res := range resources { fromDir := beego.AppConfig.String("userdata::location") + user + "/" + beego.AppConfig.String("userdata::projects") + "/" + project + "/" + beego.AppConfig.String("userdata::"+res+"files") toDir := beego.AppConfig.String("userdata::location") + user + "/" + beego.AppConfig.String("userdata::"+res+"files") + "/" + project res, _ := exec.Command("sh", "-c", "mount | grep \""+toDir+"\"").Output() if len(res) == 0 { beego.Trace("MOUNTING resource", res, "of project", project, "from user", user) if err := os.MkdirAll(toDir, os.ModePerm); err != nil { beego.Error("Cannot create directory", toDir) } cmd := exec.Command("sudo", "mount", "--bind", fromDir, toDir) err := cmd.Run() if err != nil { beego.Error("Cannot mount --bind ", toDir, err.Error()) } } } return nil }
func (this *UserController) processUserPasswordForm(user *models.User) { valid := validation.Validation{} userPasswordForm := UserPasswordForm{} if err := this.ParseForm(&userPasswordForm); err != nil { beego.Error(err) } _, err := valid.Valid(userPasswordForm) if err != nil { beego.Error(err) this.Abort("400") } if !user.VerifyPassword(userPasswordForm.CurrentPassword) { valid.SetError("CurrentPassword", "当前密码错误") } if len(valid.Errors) > 0 { this.Data["UserPasswordFormValidErrors"] = valid.Errors beego.Trace(fmt.Sprint(valid.Errors)) } else { user.SetPassword(userPasswordForm.Password) if err := user.Update(); err != nil { this.Abort("500") } this.FlashWrite("notice", "密码已更新!") this.Redirect(this.Ctx.Request.RequestURI, 302) } }
// InitDb initializes the database. func InitDb() { dbName := utils.Cfg.MustValue("db", "name") dbPwd := utils.Cfg.MustValue("db", "pwd_"+runtime.GOOS) // Register database. qbs.Register("mysql", fmt.Sprintf("%v:%v@%v/%v?charset=utf8&parseTime=true", utils.Cfg.MustValue("db", "user"), dbPwd, utils.Cfg.MustValue("db", "host"), dbName), dbName, qbs.NewMysql()) // Connect to database. q := connDb() defer q.Close() mg, err := setMg() if err != nil { panic("models.init -> " + err.Error()) } defer mg.Close() // Create data tables. mg.CreateTableIfNotExists(new(hv.PkgInfo)) mg.CreateTableIfNotExists(new(PkgTag)) mg.CreateTableIfNotExists(new(PkgRock)) mg.CreateTableIfNotExists(new(PkgExam)) mg.CreateTableIfNotExists(new(PkgDecl)) mg.CreateTableIfNotExists(new(PkgDoc)) mg.CreateTableIfNotExists(new(PkgFunc)) mg.CreateTableIfNotExists(new(PkgImport)) beego.Trace("Initialized database ->", dbName) }
func setEngine() { dbName := utils.Cfg.MustValue("db", "name") dbPwd := utils.Cfg.MustValue("db", "pwd_"+runtime.GOOS) if runtime.GOOS == "darwin" { u, err := user.Current() if err != nil { beego.Critical("models.init -> fail to get user:"******"db", "pwd_"+runtime.GOOS+"_"+u.Username) } var err error x, err = xorm.NewEngine("mysql", fmt.Sprintf("%v:%v@%v/%v?charset=utf8", utils.Cfg.MustValue("db", "user"), dbPwd, utils.Cfg.MustValue("db", "host"), dbName)) if err != nil { beego.Critical("models.init -> fail to conntect database:", err.Error()) os.Exit(2) } if beego.RunMode != "pro" { x.ShowDebug = true x.ShowErr = true //x.ShowSQL = true } beego.Trace("Initialized database ->", dbName) }
func GetGoSubrepo() (pinfos []hv.PkgInfo) { err := x.Where("is_go_subrepo = ?", true).Asc("import_path").Find(&pinfos) if err != nil { beego.Trace("models.GetGoSubrepo ->", err) } return pinfos }
func init() { // Try to have highest performance. runtime.GOMAXPROCS(runtime.NumCPU()) // Set application log level. beego.SetLevel(beego.LevelTrace) // Initialize log file. os.Mkdir("./log", os.ModePerm) // Compute log file name as format '<year>-<month>-<day>.txt', eg.'2013-5-6.txt'. logName := fmt.Sprintf("./log/%d-%d-%d.txt", time.Now().Year(), time.Now().Month(), time.Now().Day()) // Open or create log file. var fl *os.File var err error if utils.IsExist(logName) { fl, err = os.OpenFile(logName, os.O_RDWR|os.O_APPEND, 0644) } else { fl, err = os.Create(logName) } if err != nil { beego.Trace("Failed to init log file ->", err) return } beego.Info("Go Walker", VERSION) beego.SetLogger(log.New(fl, "", log.Ldate|log.Ltime)) }
func (this *ModifyController) Post() { ///check islogin session := this.GetSession("Admin") if session == nil { beego.Trace("session verify failed!") this.Redirect("/", 302) return } //get form info mac := this.Input().Get("mac") newmac := this.Input().Get("newmac") deviceinfo := models.Deviceinfo{ Mac: mac, } //check mac address format if !CheckMacFormat(newmac) { beego.Error(newmac, "not a mac address!") router := "/modify?mac=" router += mac this.Redirect(router, 302) return } //write to db ok := models.ModifyDevice(&deviceinfo, newmac) if ok { beego.Info("ModifyDevice success!") this.Redirect("/noregister", 301) return } beego.Info("ModifyDevice failed! Once again") this.Data["HadModified"] = false }
func FlushCache() { // Flush cache projects. num := len(cachePros) models.FlushCacheProjects(cachePros) beego.Trace("FlushCacheProjects #", num) cachePros = make([]hv.PkgInfo, 0, num) }
func (c *MainController) Get() { c.Ctx.WriteString("appname: " + beego.AppConfig.String("appname") + "\nhttpport: " + beego.AppConfig.String("httpport") + "\nrunmode: " + beego.AppConfig.String("runmode")) c.Ctx.WriteString("\n\nappname: " + beego.AppName + "\nhttpport: " + strconv.Itoa(beego.HttpPort) + "\nrunmode: " + beego.RunMode) beego.Trace("trace test1..") beego.Info("test1...") beego.SetLevel(beego.LevelInformational) beego.Trace("trace test2..") beego.Info("test2...") }
func (this *MainController) Get() { // 配置管理 this.Ctx.WriteString("AppName: " + beego.AppConfig.String("appname") + "\nRunMode: " + beego.AppConfig.String("runmode")) // 默认参数 this.Ctx.WriteString("\n\nAppName: " + beego.AppName + "\nRunMode: " + beego.RunMode) // 日志级别 beego.Trace("Trace test1") beego.Info("Info test1") beego.SetLevel(beego.LevelInfo) beego.Trace("Trace test2") beego.Info("Info test2") }
//注册页面,现实错误信息 func (this *AuthController) registerPageWithErrors(form RegisterForm, errors []*validation.ValidationError) { this.Data["PageTitle"] = fmt.Sprintf("注册 | %s", setting.AppName) this.Layout = "layout.html" this.TplNames = "register.html" this.Data["form"] = form this.Data["errors"] = errors this.Data["HasError"] = true beego.Trace(errors[0]) }
func main() { beego.Trace("Log is ok") //stmt, err := db.Prepare("select * from account") rows, err := DB.Query("select id from account") checkErr(err) var id int for rows.Next() { rows.Scan(&id) beego.Trace("======================", id, "===========================") } rows.Close() tx, err := DB.Begin() checkErr(err) tx.Commit() //db. DB.Close() beego.Run() }
//输入email,发送重设密码邮件 func (this *AuthController) ForgetPassword() { this.Data["PageTitle"] = fmt.Sprintf("忘记密码 | %s", setting.AppName) this.Layout = "layout.html" this.TplNames = "forget-password.html" valid := validation.Validation{} form := ForgetPasswordForm{} if this.Ctx.Request.Method == "POST" { if err := this.ParseForm(&form); err != nil { beego.Error(err) } _, err := valid.Valid(form) if err != nil { beego.Error(err) } user := models.User{Email: form.Email} if err := user.Read("Email"); err != nil { beego.Trace(user) beego.Trace(form) valid.SetError("Email", "此电子邮件并未注册") } beego.Trace(valid.Errors) if len(valid.Errors) == 0 { //发送忘记密码邮件 code, err := user.GenerateActivateCode() if err != nil { this.Abort("500") } sub := sendcloud.NewSubstitution() sub.AddTo(user.Email) sub.AddSub("%appname%", setting.AppName) sub.AddSub("%name%", user.Username) sub.AddSub("%url%", setting.AppUrl+beego.UrlFor("AuthController.ResetPassword", ":code", code)) if err := setting.Sendcloud.SendTemplate("gotalk_password", setting.AppName+"忘记密码", setting.From, setting.FromName, sub); err != nil { beego.Error(err) } this.FlashWrite("notice", fmt.Sprintf("重设密码的方法已经发到%s。请查收!", user.Email)) this.Redirect("/", 302) } else { this.Data["HasError"] = true this.Data["errors"] = valid.Errors } } }
func (this *VerifyController) Get() { //check islogin session := this.GetSession("Admin") if session == nil { beego.Trace("session verify failed!") this.Redirect("/", 302) return } this.TplNames = "login.html" }
func (this *HomeController) Post() { //session认证 session := this.GetSession("Admin") if session == nil { beego.Trace("session verify failed!") this.Redirect("/", 302) return } this.TplNames = "login.html" }
func (this *ShowScriptController) Post() { //用户身份认证 session := this.GetSession("Admin") if session == nil { beego.Trace("session verify failed!") this.Redirect("/", 302) return } }
func (this *DeviceinfoController) Post() { //session认证 session := this.GetSession("Admin") if session == nil { beego.Trace("session verify failed!") this.Redirect("/", 302) return } this.Redirect("/", 302) return }
func (this *ImportController) Get() { //check islogin session := this.GetSession("Admin") if session == nil { beego.Trace("session verify failed!") this.Redirect("/", 302) return } this.Data["IsImported"] = false this.TplNames = "import.html" }