func (this *AuthController) renderLoginPage(sig, callback string) { this.Data["CanRegister"] = g.Config().CanRegister this.Data["LdapEnabled"] = g.Config().Ldap.Enabled this.Data["Sig"] = sig this.Data["Callback"] = callback this.TplNames = "auth/login.html" }
/** * @function name: func (this *AuthController) LoginWithToken() * @description: This function logins user with third party token. * @related issues: OWL-247, OWL-206 * @param: void * @return: void * @author: Don Hsieh * @since: 12/16/2015 * @last modified: 01/08/2016 * @called by: beego.Router("/auth/login/:token", &AuthController{}, "get:LoginWithToken") * in fe/http/uic/uic_routes.go */ func (this *AuthController) LoginWithToken() { log.Println("func (this *AuthController) LoginWithToken()") token := this.Ctx.Input.Param(":token") log.Println("token =", token) key := g.Config().Api.Key authUrl := g.Config().Api.Access + "/" + token + "/" + key nodes := getRequest(authUrl) if status, ok := nodes["status"]; ok { if int(status.(float64)) == 1 { data := nodes["data"].(map[string]interface{}) access_key := data["access_key"].(string) username := data["username"].(string) email := data["email"].(string) log.Println("access_key =", access_key) urlRole := g.Config().Api.Role + "/" + access_key nodes := getRequest(urlRole) role := 3 if int(nodes["status"].(float64)) == 1 { permission := nodes["data"] log.Println("permission =", permission) if permission == "admin" { role = 0 } else if permission == "operator" { role = 1 } else if permission == "observer" { role = 2 } else if permission == "deny" { role = 3 } maxAge := 3600 * 24 * 30 this.Ctx.SetCookie("token", access_key, maxAge, "/") this.Ctx.SetCookie("token", access_key, maxAge, "/", g.Config().Http.Cookie) } user := ReadUserByName(username) if user == nil { // create third party user InsertRegisterUser(username, "") user = ReadUserByName(username) } if len(user.Passwd) == 0 { user.Email = email user.Role = role user.Update() } appSig := this.GetString("sig", "") callback := this.GetString("callback", "") if appSig != "" && callback != "" { SaveSessionAttrs(user.Id, appSig, int(time.Now().Unix())+3600*24*30) } else { this.CreateSession(user.Id, 3600*24*30) } this.Redirect("/me/info", 302) } } // not logged in. redirect to login page. appSig := this.GetString("sig", "") callback := this.GetString("callback", "") this.renderLoginPage(appSig, callback) }
func (this *UserController) ChangePassword() { oldPassword := strings.TrimSpace(this.GetString("old_password", "")) newPassword := strings.TrimSpace(this.GetString("new_password", "")) repeatPassword := strings.TrimSpace(this.GetString("repeat_password", "")) if newPassword != repeatPassword { this.ServeErrJson("password not equal the repeart one") return } me := this.Ctx.Input.GetData("CurrentUser").(*User) if me.Passwd != str.Md5Encode(g.Config().Salt+oldPassword) { this.ServeErrJson("old password error") return } newPass := str.Md5Encode(g.Config().Salt + newPassword) if me.Passwd == newPass { this.ServeOKJson() return } me.Passwd = newPass _, err := me.Update() if err != nil { this.ServeErrJson("occur error " + err.Error()) return } RemoveSessionByUid(me.Id) this.ServeOKJson() }
/** * @function name: func (this *AuthController) LoginThirdParty() * @description: This function returns third party login URL. * @related issues: OWL-206 * @param: void * @return: void * @author: Don Hsieh * @since: 12/17/2015 * @last modified: 12/17/2015 * @called by: beego.Router("/auth/third-party", &AuthController{}, "post:LoginThirdParty") * in fe/http/uic/uic_routes.go */ func (this *AuthController) LoginThirdParty() { s := g.Config().Api.Redirect s = base64.StdEncoding.EncodeToString([]byte(s)) strEncoded := url.QueryEscape(s) loginUrl := g.Config().Api.Login + "/" + strEncoded this.ServeDataJson(loginUrl) }
func main() { cfg := flag.String("c", "cfg.json", "configuration file") version := flag.Bool("v", false, "show version") flag.Parse() if *version { fmt.Println(g.VERSION) os.Exit(0) } // parse config if err := g.ParseConfig(*cfg); err != nil { log.Fatalln(err) } conf := g.Config() logger.SetLevelWithDefault(g.Config().Log, "info") model.InitDatabase() cache.InitCache() if conf.Grpc.Enabled { graph.Start() go grpc.Start() } if conf.Mq.Enabled { go mq.Start() } if conf.Http.Enabled { go http.Start() } select {} }
func (this *AuthController) RegisterPost() { if !g.Config().CanRegister { this.ServeErrJson("registration system is not open") return } name := strings.TrimSpace(this.GetString("name", "")) password := strings.TrimSpace(this.GetString("password", "")) repeatPassword := strings.TrimSpace(this.GetString("repeat_password", "")) if password != repeatPassword { this.ServeErrJson("password not equal the repeart one") return } if !utils.IsUsernameValid(name) { this.ServeErrJson("name pattern is invalid") return } if ReadUserIdByName(name) > 0 { this.ServeErrJson("name is already existent") return } lastId, err := InsertRegisterUser(name, str.Md5Encode(g.Config().Salt+password)) if err != nil { this.ServeErrJson("insert user fail " + err.Error()) return } this.CreateSession(lastId, 3600*24*30) this.ServeOKJson() }
func (this *AuthApiController) UpdateUser() { baseResp := this.BasicRespGen() _, err := this.SessionCheck() if err != nil { this.ResposeError(baseResp, err.Error()) return } else { username := this.GetString("cName", this.Ctx.GetCookie("name")) user := ReadUserByName(username) user.Email = strings.TrimSpace(this.GetString("email", user.Email)) user.Cnname = strings.TrimSpace(this.GetString("cnname", user.Cnname)) user.IM = strings.TrimSpace(this.GetString("im", user.IM)) user.QQ = strings.TrimSpace(this.GetString("qq", user.QQ)) user.Phone = strings.TrimSpace(this.GetString("phone", user.Phone)) passwdtmp := strings.TrimSpace(this.GetString("password", "")) oldpasswdtmp := strings.TrimSpace(this.GetString("oldpassword", "")) if passwdtmp != "" { if user.Passwd != str.Md5Encode(g.Config().Salt+oldpasswdtmp) { this.ResposeError(baseResp, "original password is empty or the password you inputed is not matched the original one.") return } else { user.Passwd = str.Md5Encode(g.Config().Salt + passwdtmp) } } _, err := user.Update() if err != nil { this.ResposeError(baseResp, err.Error()) return } } this.ServeApiJson(baseResp) return }
/** * @function name: func (this *AuthController) LoginWithToken() * @description: This function logins user with third party token. * @related issues: OWL-247, OWL-206 * @param: void * @return: void * @author: Don Hsieh * @since: 12/16/2015 * @last modified: 01/08/2016 * @called by: beego.Router("/auth/login/:token", &AuthController{}, "get:LoginWithToken") * in fe/http/uic/uic_routes.go */ func (this *AuthController) LoginWithToken() { log.Println("func (this *AuthController) LoginWithToken()") token := this.Ctx.Input.Param(":token") log.Println("token =", token) key := g.Config().Api.Key authUrl := g.Config().Api.Access + "/" + token + "/" + key nodes := sendHttpGetRequest(authUrl) if nodes == nil { nodes = sendHttpGetRequest(authUrl) } log.Println("nodes =", nodes) var userInfo = make(map[string]string) userInfo["username"] = "" userInfo["email"] = "" userInfo["access_key"] = "" if nodes != nil { setUserInfo(nodes, userInfo) } log.Println("userInfo =", userInfo) username := userInfo["username"] if len(username) > 0 { access_key := userInfo["access_key"] user := ReadUserByName(username) if user == nil { // create third party user InsertRegisterUser(username, "", "") user = ReadUserByName(username) } if len(user.Passwd) == 0 { role := getUserRole(access_key) if role < 1 { role = getUserRole(access_key) } email := userInfo["email"] user.Email = email user.Role = role user.Update() } maxAge := 3600 * 24 * 30 this.Ctx.SetCookie("token", access_key, maxAge, "/") this.Ctx.SetCookie("token", access_key, maxAge, "/", g.Config().Http.Cookie) appSig := this.GetString("sig", "") callback := this.GetString("callback", "") if appSig != "" && callback != "" { SaveSessionAttrs(user.Id, appSig, int(time.Now().Unix())+3600*24*30) } else { this.CreateSession(user.Id, 3600*24*30) } this.Redirect("/me/info", 302) } else { // not logged in. redirect to login page. appSig := this.GetString("sig", "") callback := this.GetString("callback", "") this.renderLoginPage(appSig, callback) } }
func (this *AuthController) CreateSession(uid int64, maxAge int) int { sig := utils.GenerateUUID() user := SelectUserById(uid) expired := int(time.Now().Unix()) + maxAge SaveSessionAttrs(uid, sig, expired) this.Ctx.SetCookie("sig", sig, maxAge, "/") this.Ctx.SetCookie("sig", sig, maxAge, "/", g.Config().Http.Cookie) this.Ctx.SetCookie("name", user.Name, maxAge, "/") this.Ctx.SetCookie("name", user.Name, maxAge, "/", g.Config().Http.Cookie) return expired }
func Start() { if !g.Config().Http.Enabled { return } addr := g.Config().Http.Listen if addr == "" { return } home.ConfigRoutes() uic.ConfigRoutes() beego.AddFuncMap("member", uic_model.MembersByTeamId) beego.Run(addr) }
func (this *AuthController) Logout() { u := this.Ctx.Input.GetData("CurrentUser").(*User) token := this.Ctx.GetCookie("token") if len(token) > 0 { url := g.Config().Api.Logout + "/" + token log.Println("logout url =", url) result := getRequest(url) log.Println("logout result =", result) this.Ctx.SetCookie("token", "", 0, "/") this.Ctx.SetCookie("token", "", 0, "/", g.Config().Http.Cookie) } RemoveSessionByUid(u.Id) this.Ctx.SetCookie("sig", "", 0, "/") this.Ctx.SetCookie("sig", "", 0, "/", g.Config().Http.Cookie) this.Redirect("/auth/login", 302) }
func (this *UserController) Users() { query := strings.TrimSpace(this.GetString("query", "")) if utils.HasDangerousCharacters(query) { this.ServeErrJson("query is invalid") return } per := this.MustGetInt("per", 20) users := QueryUsers(query) total, err := users.Count() if err != nil { this.ServeErrJson("occur error " + err.Error()) return } pager := this.SetPaginator(per, total) users = users.Limit(per, pager.Offset()) var us []User _, err = users.All(&us) if err != nil { this.ServeErrJson("occur error " + err.Error()) return } me := this.Ctx.Input.GetData("CurrentUser").(*User) this.Data["Users"] = us this.Data["Query"] = query this.Data["Me"] = me this.Data["IamRoot"] = me.Name == "root" this.Data["Shortcut"] = g.Config().Shortcut this.TplName = "user/list.html" }
func QueryCounterByEndpoints(endpoints []string, limit int) (counters []string, err error) { config := g.Config() if limit == 0 || limit > config.GraphDB.Limit { limit = config.GraphDB.Limit } enp, aerr := QueryEndpointidbyNames(endpoints, limit) if aerr != nil { err = aerr return } q := orm.NewOrm() q.Using("graph") q.QueryTable("endpoint_counter") var endpoint_ids = "" for _, v := range enp { endpoint_ids += fmt.Sprintf("%d,", v.Id) } pattn, _ := regexp.Compile("\\s*,\\s*$") queryperfix := fmt.Sprintf("select distinct(counter) from endpoint_counter where endpoint_id IN(%s) limit %d", pattn.ReplaceAllString(endpoint_ids, ""), limit) var enpc []EndpointCounter _, err = q.Raw(queryperfix).QueryRows(&enpc) for _, v := range enpc { counters = append(counters, v.Counter) } return }
func QueryHostGroupByNameRegx(queryStr string, limit int) (hostgroup []HostGroup, err error) { config := g.Config() if limit == 0 || limit > config.GraphDB.LimitHostGroup { limit = config.GraphDB.LimitHostGroup } hostgroup, err = getHostGroupRegex(queryStr, limit) return }
func (this *UserController) EditGet() { me := this.Ctx.Input.GetData("CurrentUser").(*User) if me.Role <= 0 { this.ServeErrJson("no privilege") return } this.Data["User"] = this.Ctx.Input.GetData("TargetUser").(*User) this.Data["Shortcut"] = g.Config().Shortcut this.TplName = "user/edit.html" }
func (this *UserController) About() { name := this.Ctx.Input.Param(":name") u := ReadUserByName(name) if u == nil { this.NotFound("no such user") return } this.Data["User"] = u this.Data["Shortcut"] = g.Config().Shortcut this.TplName = "user/about.html" }
func Start() { if !g.Config().Http.Enabled { return } addr := g.Config().Http.Listen if addr == "" { return } home.ConfigRoutes() uic.ConfigRoutes() dashboard.ConfigRoutes() portal.ConfigRoutes() beego.AddFuncMap("member", uic_model.MembersByTeamId) beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{ AllowAllOrigins: true, })) beego.Run(addr) }
func InitDatabase() { // set default database config := g.Config() orm.RegisterDataBase("default", "mysql", config.Uic.Addr, config.Uic.Idle, config.Uic.Max) // register model orm.RegisterModel(new(User), new(Team), new(Session), new(RelTeamUser)) if config.Log == "debug" { orm.Debug = true } }
func (this *AuthApiController) Register() { baseResp := this.BasicRespGen() if !g.Config().CanRegister { this.ResposeError(baseResp, "registration system is not open") return } name := strings.TrimSpace(this.GetString("name", "")) email := strings.TrimSpace(this.GetString("email", "")) password := strings.TrimSpace(this.GetString("password", "")) repeatPassword := strings.TrimSpace(this.GetString("repeatPassword", "")) var lastID int64 var err error switch { case password != repeatPassword: this.ResposeError(baseResp, "password not equal the repeart one") return case !utils.IsUsernameValid(name): this.ResposeError(baseResp, "name pattern is invalid") return case ReadUserIdByName(name) > 0: this.ResposeError(baseResp, "name is already existent") return default: lastID, err = InsertRegisterUser(name, str.Md5Encode(g.Config().Salt+password), email) if err != nil { this.ResposeError(baseResp, "insert user fail "+err.Error()) return } } sig, expired := this.CreateSession(lastID, 3600*24*30) baseResp.Data["name"] = name baseResp.Data["sig"] = sig baseResp.Data["expired"] = expired this.ServeApiJson(baseResp) return }
func InitDatabase() { // set default database // databases_name, sql_derver, db_addr, idle_time, mix_connection config := g.Config() orm.RegisterDataBase("default", "mysql", config.Uic.Addr, config.Uic.Idle, config.Uic.Max) orm.RegisterDataBase("graph", "mysql", config.GraphDB.Addr, config.GraphDB.Idle, config.GraphDB.Max) orm.RegisterDataBase("falcon_portal", "mysql", config.FalconPortal.Addr, config.FalconPortal.Idle, config.FalconPortal.Max) // register model orm.RegisterModel(new(uic.User), new(uic.Team), new(uic.Session), new(uic.RelTeamUser), new(dashboard.Endpoint), new(dashboard.EndpointCounter), new(dashboard.HostGroup), new(dashboard.Hosts), new(event.EventCases), new(event.Events), new(event.Tpl)) if config.Log == "debug" { orm.Debug = true } }
func InitCache() { cfg := g.Config() if !cfg.Cache.Enabled { return } cache.InitCache( cfg.Cache.Redis, cfg.Cache.Idle, cfg.Cache.Max, time.Duration(cfg.Cache.Timeout.Conn)*time.Millisecond, time.Duration(cfg.Cache.Timeout.Read)*time.Millisecond, time.Duration(cfg.Cache.Timeout.Write)*time.Millisecond, time.Hour, ) }
func GetEvents(startTime int64, endTime int64, status string, limit int) (result []EventsRsp, err error) { config := g.Config() if limit == 0 || limit > config.FalconPortal.Limit { limit = config.FalconPortal.Limit } q := orm.NewOrm() q.Using("falcon_portal") queryTmp := "" if status != "ALL" { queryTmp = fmt.Sprintf(" %v status = '%s' and ", queryTmp, status) } if startTime != 0 && endTime != 0 { queryTmp = fmt.Sprintf(" %v events.timestamp >= %d and events.timestamp <= %d", queryTmp, startTime, endTime) } if queryTmp != "" { _, err = q.Raw(fmt.Sprintf(`SELECT events.id as id, events.step as step, events.cond as cond, events.timestamp as timestamp, events.event_caseId as eid, event_cases.tpl_creator as tpl_creator, event_cases.metric as metric, event_cases.endpoint as endpoint FROM events LEFT JOIN event_cases on event_cases.id = events.event_caseId WHERE %v ORDER BY events.timestamp DESC limit %d`, queryTmp, limit)).QueryRows(&result) } else { _, err = q.Raw(fmt.Sprintf(`SELECT events.id as id, events.step as step, events.cond as cond, events.timestamp as timestamp, events.event_caseId as eid, event_cases.tpl_creator as tpl_creator, event_cases.metric as metric, event_cases.endpoint as endpoint FROM events LEFT JOIN event_cases on event_cases.id = events.event_caseId ORDER BY events.timestamp DESC limit %d`, limit)).QueryRows(&result) } if len(result) == 0 { result = []EventsRsp{} } return }
func getUserRole(access_key string) int { urlRole := g.Config().Api.Role + "/" + access_key nodes := sendHttpGetRequest(urlRole) role := -1 if int(nodes["status"].(float64)) == 1 { permission := nodes["data"] log.Println("permission =", permission) if permission == "admin" { role = 0 } else if permission == "operator" { role = 1 } else if permission == "observer" { role = 2 } else if permission == "deny" { role = 3 } } return role }
func (this *AuthApiController) Login() { baseResp := this.BasicRespGen() name := this.GetString("name", "") password := this.GetString("password", "") if name == "" || password == "" { this.ResposeError(baseResp, "name or password is blank") return } user := ReadUserByName(name) switch { case user == nil: this.ResposeError(baseResp, "no such user") return case user.Passwd != str.Md5Encode(g.Config().Salt+password): this.ResposeError(baseResp, "password error") return } appSig := this.GetString("sig", "") callback := this.GetString("callback", "") sig, expired := ReadSessionByName(name) switch { case sig != "": baseResp.Data["name"] = name baseResp.Data["sig"] = sig baseResp.Data["expired"] = expired case appSig != "" && callback != "": SaveSessionAttrs(user.Id, appSig, int(time.Now().Unix())+3600*24*30) baseResp.Data["name"] = name baseResp.Data["sig"] = appSig baseResp.Data["expired"] = int(time.Now().Unix()) + 3600*24*30 default: sig, expired := this.CreateSession(user.Id, 3600*24*30) baseResp.Data["name"] = name baseResp.Data["sig"] = sig baseResp.Data["expired"] = expired } this.ServeApiJson(baseResp) return }
func (this *UserController) CreateRoot() { password := strings.TrimSpace(this.GetString("password", "")) if password == "" { this.Ctx.Output.Body([]byte("password is blank")) return } userPtr := &User{ Name: "root", Passwd: str.Md5Encode(g.Config().Salt + password), Role: 2, } _, err := userPtr.Save() if err != nil { this.Ctx.Output.Body([]byte(err.Error())) } else { this.Ctx.Output.Body([]byte("success")) } }
func (this *DashBoardController) EndpRegxquryForOps() { this.Data["Shortcut"] = g.Config().Shortcut sig := this.Ctx.GetCookie("sig") session := uic.ReadSessionBySig(sig) var username *uic.User if sig == "" || session.Uid <= 0 { this.Data["SessionFlag"] = true this.Data["ErrorMsg"] = "Session is not vaild" } else { this.Data["SessionFlag"] = false username = uic.SelectUserById(session.Uid) if username.Name != "root" { this.Data["SessionFlag"] = true this.Data["ErrorMsg"] = "You don't have permission to access this page" } } queryStr := this.GetString("queryStr", "") this.Data["QueryCondstion"] = queryStr if queryStr == "" || this.Data["SessionFlag"] == true { this.Data["Init"] = true } else { enp, _ := dashboard.QueryEndpintByNameRegxForOps(queryStr) if len(enp) > 0 { var ips []string this.Data["Endopints"] = enp this.Data["Len"] = len(enp) for _, en := range enp { if en.Ip != "" { ips = append(ips, en.Ip) } } this.Data["IP"] = strings.Join(ips, ",") } else { this.Data["Endopints"] = []string{} this.Data["Len"] = 0 this.Data["IP"] = "" } } this.TplName = "dashboard/endpoints.html" }
func (this *TeamController) Teams() { query := strings.TrimSpace(this.GetString("query", "")) if utils.HasDangerousCharacters(query) { this.ServeErrJson("query is invalid") return } per := this.MustGetInt("per", 10) me := this.Ctx.Input.GetData("CurrentUser").(*User) teams, err := QueryMineTeams(query, me.Id) if err != nil { this.ServeErrJson("occur error " + err.Error()) return } total, err := teams.Count() if err != nil { this.ServeErrJson("occur error " + err.Error()) return } pager := this.SetPaginator(per, total) teams = teams.Limit(per, pager.Offset()) var ts []Team _, err = teams.All(&ts) if err != nil { this.ServeErrJson("occur error " + err.Error()) return } this.Data["Teams"] = ts this.Data["Query"] = query this.Data["Me"] = me this.Data["IamRoot"] = me.Name == "root" this.Data["Shortcut"] = g.Config().Shortcut this.TplName = "team/list.html" }
func (this *UserController) ResetPassword() { password := this.GetString("password", "") if password == "" { this.ServeErrJson("password is blank") return } targetUser := this.Ctx.Input.GetData("TargetUser").(*User) if targetUser.Name == "root" { this.ServeErrJson("no privilege") return } targetUser.Passwd = str.Md5Encode(g.Config().Salt + password) _, err := targetUser.Update() if err != nil { this.ServeErrJson("occur error " + err.Error()) return } this.ServeOKJson() }
func Start() { port := fmt.Sprintf(":%v", g.Config().Grpc.Port) log.Printf("start grpc in port %v ..", port) //queryrrd(1452806153, 1452827753, "AVERAGE", "docker-agent", "cpu.idle") lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } //recovery panic error defer func() { if r := recover(); r != nil { var ok bool err, ok = r.(error) if !ok { err = fmt.Errorf("grpc service got error: %v", r) } } }() s := grpc.NewServer() pb.RegisterOwlQueryServer(s, &server{}) s.Serve(lis) }
func (this *TeamController) CreateTeamGet() { this.Data["Shortcut"] = g.Config().Shortcut this.TplName = "team/create.html" }