本文整理汇总了Golang中github.com/wangy1931/grafana/pkg/bus.Dispatch函数的典型用法代码示例。如果您正苦于以下问题:Golang Dispatch函数的具体用法?Golang Dispatch怎么用?Golang Dispatch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Dispatch函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: ChangeUserPassword
func ChangeUserPassword(c *middleware.Context, cmd m.ChangeUserPasswordCommand) Response {
userQuery := m.GetUserByIdQuery{Id: c.UserId}
if err := bus.Dispatch(&userQuery); err != nil {
return ApiError(500, "Could not read user from database", err)
}
passwordHashed := util.EncodePassword(cmd.OldPassword, userQuery.Result.Salt)
if passwordHashed != userQuery.Result.Password {
return ApiError(401, "Invalid old password", nil)
}
if len(cmd.NewPassword) < 4 {
return ApiError(400, "New password too short", nil)
}
cmd.UserId = c.UserId
cmd.NewPassword = util.EncodePassword(cmd.NewPassword, userQuery.Result.Salt)
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Failed to change user password", err)
}
return ApiSuccess("User password changed")
}
开发者ID:wangy1931,项目名称:grafana,代码行数:25,代码来源:user.go
示例2: inviteExistingUserToOrg
func inviteExistingUserToOrg(c *middleware.Context, user *m.User, inviteDto *dtos.AddInviteForm) Response {
// user exists, add org role
createOrgUserCmd := m.AddOrgUserCommand{OrgId: c.OrgId, UserId: user.Id, Role: inviteDto.Role}
if err := bus.Dispatch(&createOrgUserCmd); err != nil {
if err == m.ErrOrgUserAlreadyAdded {
return ApiError(412, fmt.Sprintf("User %s is already added to organization", inviteDto.LoginOrEmail), err)
}
return ApiError(500, "Error while trying to create org user", err)
} else {
if !inviteDto.SkipEmails && util.IsEmail(user.Email) {
emailCmd := m.SendEmailCommand{
To: []string{user.Email},
Template: "invited_to_org.html",
Data: map[string]interface{}{
"Name": user.NameOrFallback(),
"OrgName": c.OrgName,
"InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login),
},
}
if err := bus.Dispatch(&emailCmd); err != nil {
return ApiError(500, "Failed to send email invited_to_org", err)
}
}
return ApiSuccess(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName))
}
}
开发者ID:wangy1931,项目名称:grafana,代码行数:29,代码来源:org_invite.go
示例3: AdminUpdateUserPassword
func AdminUpdateUserPassword(c *middleware.Context, form dtos.AdminUpdateUserPasswordForm) {
userId := c.ParamsInt64(":id")
if len(form.Password) < 4 {
c.JsonApiErr(400, "New password too short", nil)
return
}
userQuery := m.GetUserByIdQuery{Id: userId}
if err := bus.Dispatch(&userQuery); err != nil {
c.JsonApiErr(500, "Could not read user from database", err)
return
}
passwordHashed := util.EncodePassword(form.Password, userQuery.Result.Salt)
cmd := m.ChangeUserPasswordCommand{
UserId: userId,
NewPassword: passwordHashed,
}
if err := bus.Dispatch(&cmd); err != nil {
c.JsonApiErr(500, "Failed to update user password", err)
return
}
c.JsonOK("User password updated")
}
开发者ID:wangy1931,项目名称:grafana,代码行数:29,代码来源:admin_users.go
示例4: SignUp
// POST /api/user/signup
func SignUp(c *middleware.Context, form dtos.SignUpForm) Response {
if !setting.AllowUserSignUp {
return ApiError(401, "User signup is disabled", nil)
}
existing := m.GetUserByLoginQuery{LoginOrEmail: form.Email}
if err := bus.Dispatch(&existing); err == nil {
return ApiError(422, "User with same email address already exists", nil)
}
cmd := m.CreateTempUserCommand{}
cmd.OrgId = -1
cmd.Email = form.Email
cmd.Status = m.TmpUserSignUpStarted
cmd.InvitedByUserId = c.UserId
cmd.Code = util.GetRandomString(20)
cmd.RemoteAddr = c.Req.RemoteAddr
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Failed to create signup", err)
}
bus.Publish(&events.SignUpStarted{
Email: form.Email,
Code: cmd.Code,
})
metrics.M_Api_User_SignUpStarted.Inc(1)
return Json(200, util.DynMap{"status": "SignUpCreated"})
}
开发者ID:wangy1931,项目名称:grafana,代码行数:32,代码来源:signup.go
示例5: EnsureAdminUser
func EnsureAdminUser() {
statsQuery := m.GetSystemStatsQuery{}
if err := bus.Dispatch(&statsQuery); err != nil {
log.Fatal(3, "Could not determine if admin user exists: %v", err)
return
}
if statsQuery.Result.UserCount > 0 {
return
}
cmd := m.CreateUserCommand{}
cmd.Login = setting.AdminUser
cmd.Email = setting.AdminUser + "@localhost"
cmd.Password = setting.AdminPassword
cmd.IsAdmin = true
if err := bus.Dispatch(&cmd); err != nil {
log.Error(3, "Failed to create default admin user", err)
return
}
system := m.AddSystemsCommand{}
system.OrgId = cmd.Result.OrgId
system.SystemsName = []string{"Cloudwiz"}
if err := bus.Dispatch(&system); err != nil {
log.Error(3, "Failed to create defalut system for admin", err)
return
}
log.Info("Created default Cloudwiz system")
log.Info("Created default admin user: %v", setting.AdminUser)
}
开发者ID:wangy1931,项目名称:grafana,代码行数:33,代码来源:sqlstore.go
示例6: addOrgUserHelper
func addOrgUserHelper(cmd m.AddOrgUserCommand) Response {
if !cmd.Role.IsValid() {
return ApiError(400, "Invalid role specified", nil)
}
userQuery := m.GetUserByLoginQuery{LoginOrEmail: cmd.LoginOrEmail}
err := bus.Dispatch(&userQuery)
if err != nil {
return ApiError(404, "User not found", nil)
}
userToAdd := userQuery.Result
// if userToAdd.Id == c.UserId {
// return ApiError(400, "Cannot add yourself as user", nil)
// }
cmd.UserId = userToAdd.Id
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Could not add user to organization", err)
}
return ApiSuccess("User added to organization")
}
开发者ID:wangy1931,项目名称:grafana,代码行数:25,代码来源:org_users.go
示例7: AddOrgInvite
func AddOrgInvite(c *middleware.Context, inviteDto dtos.AddInviteForm) Response {
if !inviteDto.Role.IsValid() {
return ApiError(400, "Invalid role specified", nil)
}
// first try get existing user
userQuery := m.GetUserByLoginQuery{LoginOrEmail: inviteDto.LoginOrEmail}
if err := bus.Dispatch(&userQuery); err != nil {
if err != m.ErrUserNotFound {
return ApiError(500, "Failed to query db for existing user check", err)
}
} else {
return inviteExistingUserToOrg(c, userQuery.Result, &inviteDto)
}
cmd := m.CreateTempUserCommand{}
cmd.OrgId = c.OrgId
cmd.Email = inviteDto.LoginOrEmail
cmd.Name = inviteDto.Name
cmd.Status = m.TmpUserInvitePending
cmd.InvitedByUserId = c.UserId
cmd.Code = util.GetRandomString(30)
cmd.Role = inviteDto.Role
cmd.RemoteAddr = c.Req.RemoteAddr
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Failed to save invite to database", err)
}
system_user := m.AddSystemsUserCommand{}
system_user.InviteCode = cmd.Result.Code
system_user.SystemsId = inviteDto.Systems
if err := bus.Dispatch(&system_user); err != nil {
return ApiError(500, "Failed to save system_user to database", err)
}
// send invite email
if !inviteDto.SkipEmails && util.IsEmail(inviteDto.LoginOrEmail) {
emailCmd := m.SendEmailCommand{
To: []string{inviteDto.LoginOrEmail},
Template: "new_user_invite.html",
Data: map[string]interface{}{
"Name": util.StringsFallback2(cmd.Name, cmd.Email),
"OrgName": c.OrgName,
"Email": c.Email,
"LinkUrl": setting.ToAbsUrl("invite/" + cmd.Code),
"InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login),
},
}
if err := bus.Dispatch(&emailCmd); err != nil {
return ApiError(500, "Failed to send email invite", err)
}
return ApiSuccess(fmt.Sprintf("Sent invite to %s", inviteDto.LoginOrEmail))
}
return ApiSuccess(fmt.Sprintf("Created invite for %s", inviteDto.LoginOrEmail))
}
开发者ID:wangy1931,项目名称:grafana,代码行数:58,代码来源:org_invite.go
示例8: sendUsageStats
func sendUsageStats() {
log.Trace("Sending anonymous usage stats to stats.grafana.org")
version := strings.Replace(setting.BuildVersion, ".", "_", -1)
metrics := map[string]interface{}{}
report := map[string]interface{}{
"version": version,
"metrics": metrics,
}
UsageStats.Each(func(name string, i interface{}) {
switch metric := i.(type) {
case Counter:
if metric.Count() > 0 {
metrics[name+".count"] = metric.Count()
metric.Clear()
}
}
})
statsQuery := m.GetSystemStatsQuery{}
if err := bus.Dispatch(&statsQuery); err != nil {
log.Error(3, "Failed to get system stats", err)
return
}
metrics["stats.dashboards.count"] = statsQuery.Result.DashboardCount
metrics["stats.users.count"] = statsQuery.Result.UserCount
metrics["stats.orgs.count"] = statsQuery.Result.OrgCount
dsStats := m.GetDataSourceStatsQuery{}
if err := bus.Dispatch(&dsStats); err != nil {
log.Error(3, "Failed to get datasource stats", err)
return
}
// send counters for each data source
// but ignore any custom data sources
// as sending that name could be sensitive information
dsOtherCount := 0
for _, dsStat := range dsStats.Result {
if m.IsKnownDataSourcePlugin(dsStat.Type) {
metrics["stats.ds."+dsStat.Type+".count"] = dsStat.Count
} else {
dsOtherCount += dsStat.Count
}
}
metrics["stats.ds.other.count"] = dsOtherCount
out, _ := json.MarshalIndent(report, "", " ")
data := bytes.NewBuffer(out)
client := http.Client{Timeout: time.Duration(5 * time.Second)}
go client.Post("https://stats.grafana.org/grafana-usage-report", "application/json", data)
}
开发者ID:wangy1931,项目名称:grafana,代码行数:56,代码来源:report_usage.go
示例9: CompleteInvite
func CompleteInvite(c *middleware.Context, completeInvite dtos.CompleteInviteForm) Response {
query := m.GetTempUserByCodeQuery{Code: completeInvite.InviteCode}
if err := bus.Dispatch(&query); err != nil {
if err == m.ErrTempUserNotFound {
return ApiError(404, "Invite not found", nil)
}
return ApiError(500, "Failed to get invite", err)
}
invite := query.Result
if invite.Status != m.TmpUserInvitePending {
return ApiError(412, fmt.Sprintf("Invite cannot be used in status %s", invite.Status), nil)
}
cmd := m.CreateUserCommand{
Email: completeInvite.Email,
Name: completeInvite.Name,
Login: completeInvite.Username,
Password: completeInvite.Password,
SkipOrgSetup: true,
}
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "failed to create user", err)
}
user := &cmd.Result
system_user := m.UpdateUserSystemCommond{}
system_user.InviteCode = completeInvite.InviteCode
system_user.UserId = user.Id
if err := bus.Dispatch(&system_user); err != nil {
return ApiError(500, "failed to update system user ", err)
}
bus.Publish(&events.SignUpCompleted{
Name: user.NameOrFallback(),
Email: user.Email,
})
if ok, rsp := applyUserInvite(user, invite, true); !ok {
return rsp
}
loginUserWithUser(user, c)
metrics.M_Api_User_SignUpCompleted.Inc(1)
metrics.M_Api_User_SignUpInvite.Inc(1)
return ApiSuccess("User created and logged in")
}
开发者ID:wangy1931,项目名称:grafana,代码行数:52,代码来源:org_invite.go
示例10: Search
func Search(c *middleware.Context) {
query := c.Query("query")
tags := c.QueryStrings("tag")
starred := c.Query("starred")
limit := c.QueryInt("limit")
if limit == 0 {
limit = 1000
}
searchQuery := search.Query{
Title: query,
Tags: tags,
UserId: c.UserId,
Limit: limit,
IsStarred: starred == "true",
OrgId: c.OrgId,
}
err := bus.Dispatch(&searchQuery)
if err != nil {
c.JsonApiErr(500, "Search failed", err)
return
}
dashQuery := m.GetCurrentDashboardDashboard{}
dashQuery.UserId = c.UserId
err = bus.Dispatch(&dashQuery)
if err != nil {
c.JsonApiErr(500, "Get Dasboard Id failed", err)
return
}
if c.OrgRole != "Admin" || !c.IsGrafanaAdmin {
for index, hit := range searchQuery.Result {
isDelete := true
for _, dash := range dashQuery.Result {
if dash.Id == hit.Id {
isDelete = false
}
}
if isDelete {
last := index + 1
if last > len(searchQuery.Result) {
last = len(searchQuery.Result)
}
searchQuery.Result = append(searchQuery.Result[:index], searchQuery.Result[last:]...)
}
}
}
c.JSON(200, searchQuery.Result)
}
开发者ID:wangy1931,项目名称:grafana,代码行数:52,代码来源:search.go
示例11: SendResetPasswordEmail
func SendResetPasswordEmail(c *middleware.Context, form dtos.SendResetPasswordEmailForm) Response {
userQuery := m.GetUserByLoginQuery{LoginOrEmail: form.UserOrEmail}
if err := bus.Dispatch(&userQuery); err != nil {
return ApiError(404, "User does not exist", err)
}
emailCmd := m.SendResetPasswordEmailCommand{User: userQuery.Result}
if err := bus.Dispatch(&emailCmd); err != nil {
return ApiError(500, "Failed to send email", err)
}
return ApiSuccess("Email sent")
}
开发者ID:wangy1931,项目名称:grafana,代码行数:14,代码来源:password.go
示例12: CreateDashboardSnapshot
func CreateDashboardSnapshot(c *middleware.Context, cmd m.CreateDashboardSnapshotCommand) {
if cmd.External {
// external snapshot ref requires key and delete key
if cmd.Key == "" || cmd.DeleteKey == "" {
c.JsonApiErr(400, "Missing key and delete key for external snapshot", nil)
return
}
cmd.OrgId = -1
cmd.UserId = -1
metrics.M_Api_Dashboard_Snapshot_External.Inc(1)
} else {
cmd.Key = util.GetRandomString(32)
cmd.DeleteKey = util.GetRandomString(32)
cmd.OrgId = c.OrgId
cmd.UserId = c.UserId
metrics.M_Api_Dashboard_Snapshot_Create.Inc(1)
}
if err := bus.Dispatch(&cmd); err != nil {
c.JsonApiErr(500, "Failed to create snaphost", err)
return
}
c.JSON(200, util.DynMap{
"key": cmd.Key,
"deleteKey": cmd.DeleteKey,
"url": setting.ToAbsUrl("dashboard/snapshot/" + cmd.Key),
"deleteUrl": setting.ToAbsUrl("api/snapshots-delete/" + cmd.DeleteKey),
})
}
开发者ID:wangy1931,项目名称:grafana,代码行数:31,代码来源:dashboard_snapshot.go
示例13: CreateOrg
// POST /api/orgs
func CreateOrg(c *middleware.Context, cmd m.CreateOrgCommand) Response {
if !c.IsSignedIn || (!setting.AllowUserOrgCreate && !c.IsGrafanaAdmin) {
return ApiError(403, "Access denied", nil)
}
cmd.UserId = c.UserId
if err := bus.Dispatch(&cmd); err != nil {
if err == m.ErrOrgNameTaken {
return ApiError(400, "Organization name taken", err)
}
return ApiError(500, "Failed to create organization", err)
}
metrics.M_Api_Org_Create.Inc(1)
// We need to add the data source defined in config for this org to data_source table
if err := sqlstore.AddDatasourceForOrg(cmd.Result.Id); err != nil {
return ApiError(500, "Failed to add data source for organization", err)
}
return Json(200, &util.DynMap{
"orgId": cmd.Result.Id,
"message": "Organization created",
})
}
开发者ID:wangy1931,项目名称:grafana,代码行数:26,代码来源:org.go
示例14: getGrafanaUserFor
func (a *ldapAuther) getGrafanaUserFor(ldapUser *ldapUserInfo) (*m.User, error) {
// validate that the user has access
// if there are no ldap group mappings access is true
// otherwise a single group must match
access := len(a.server.LdapGroups) == 0
for _, ldapGroup := range a.server.LdapGroups {
if ldapUser.isMemberOf(ldapGroup.GroupDN) {
access = true
break
}
}
if !access {
log.Info("Ldap Auth: user %s does not belong in any of the specified ldap groups, ldapUser groups: %v", ldapUser.Username, ldapUser.MemberOf)
return nil, ErrInvalidCredentials
}
// get user from grafana db
userQuery := m.GetUserByLoginQuery{LoginOrEmail: ldapUser.Username}
if err := bus.Dispatch(&userQuery); err != nil {
if err == m.ErrUserNotFound {
return a.createGrafanaUser(ldapUser)
} else {
return nil, err
}
}
return userQuery.Result, nil
}
开发者ID:wangy1931,项目名称:grafana,代码行数:29,代码来源:ldap.go
示例15: GetDashboardSnapshot
func GetDashboardSnapshot(c *middleware.Context) {
key := c.Params(":key")
query := &m.GetDashboardSnapshotQuery{Key: key}
err := bus.Dispatch(query)
if err != nil {
c.JsonApiErr(500, "Failed to get dashboard snapshot", err)
return
}
snapshot := query.Result
// expired snapshots should also be removed from db
if snapshot.Expires.Before(time.Now()) {
c.JsonApiErr(404, "Dashboard snapshot not found", err)
return
}
dto := dtos.DashboardFullWithMeta{
Dashboard: snapshot.Dashboard,
Meta: dtos.DashboardMeta{
Type: m.DashTypeSnapshot,
IsSnapshot: true,
Created: snapshot.Created,
Expires: snapshot.Expires,
},
}
metrics.M_Api_Dashboard_Snapshot_Get.Inc(1)
c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
c.JSON(200, dto)
}
开发者ID:wangy1931,项目名称:grafana,代码行数:34,代码来源:dashboard_snapshot.go
示例16: initContextWithApiKey
func initContextWithApiKey(ctx *Context) bool {
var keyString string
if keyString = getApiKey(ctx); keyString == "" {
return false
}
// base64 decode key
decoded, err := apikeygen.Decode(keyString)
if err != nil {
ctx.JsonApiErr(401, "Invalid API key", err)
return true
}
// fetch key
keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
if err := bus.Dispatch(&keyQuery); err != nil {
ctx.JsonApiErr(401, "Invalid API key", err)
return true
} else {
apikey := keyQuery.Result
// validate api key
if !apikeygen.IsValid(decoded, apikey.Key) {
ctx.JsonApiErr(401, "Invalid API key", err)
return true
}
ctx.IsSignedIn = true
ctx.SignedInUser = &m.SignedInUser{}
ctx.OrgRole = apikey.Role
ctx.ApiKeyId = apikey.Id
ctx.OrgId = apikey.OrgId
return true
}
}
开发者ID:wangy1931,项目名称:grafana,代码行数:34,代码来源:middleware.go
示例17: LoginPost
func LoginPost(c *middleware.Context, cmd dtos.LoginCommand) Response {
authQuery := login.LoginUserQuery{
Username: cmd.User,
Password: cmd.Password,
}
if err := bus.Dispatch(&authQuery); err != nil {
if err == login.ErrInvalidCredentials {
return ApiError(401, "Invalid username or password", err)
}
return ApiError(500, "Error while trying to authenticate user", err)
}
user := authQuery.User
loginUserWithUser(user, c)
result := map[string]interface{}{
"message": "Logged in",
}
if redirectTo, _ := url.QueryUnescape(c.GetCookie("redirect_to")); len(redirectTo) > 0 {
result["redirectUrl"] = redirectTo
c.SetCookie("redirect_to", "", -1, setting.AppSubUrl+"/")
}
metrics.M_Api_Login_Post.Inc(1)
return Json(200, result)
}
开发者ID:wangy1931,项目名称:grafana,代码行数:31,代码来源:login.go
示例18: GetDataSources
func GetDataSources(c *middleware.Context) {
log.Info("DataSource Url: %v", setting.DataSource.DataSourceUrlRoot)
query := m.GetDataSourcesQuery{OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil {
c.JsonApiErr(500, "Failed to query datasources", err)
return
}
result := make([]*dtos.DataSource, len(query.Result))
for i, ds := range query.Result {
result[i] = &dtos.DataSource{
Id: ds.Id,
OrgId: ds.OrgId,
Name: ds.Name,
Url: ds.Url,
Type: ds.Type,
Access: ds.Access,
Password: ds.Password,
Database: ds.Database,
User: ds.User,
BasicAuth: ds.BasicAuth,
IsDefault: ds.IsDefault,
}
}
c.JSON(200, result)
}
开发者ID:wangy1931,项目名称:grafana,代码行数:29,代码来源:datasources.go
示例19: UpdateSystems
func UpdateSystems(c *middleware.Context, systems dtos.UpdateSystems) Response {
if err := bus.Dispatch(&systems); err != nil {
return ApiError(500, "Failed to update Systems", err)
}
return ApiSuccess("Systems updated")
}
开发者ID:wangy1931,项目名称:grafana,代码行数:7,代码来源:systems.go
示例20: removeOrgUserHelper
func removeOrgUserHelper(orgId int64, userId int64) Response {
cmd := m.RemoveOrgUserCommand{OrgId: orgId, UserId: userId}
if err := bus.Dispatch(&cmd); err != nil {
if err == m.ErrLastOrgAdmin {
return ApiError(400, "Cannot remove last organization admin", nil)
}
return ApiError(500, "Failed to remove user from organization", err)
}
if err := bus.Dispatch(&m.DeleteUserCommand{UserId: userId}); err != nil {
return ApiError(500, "Failed to remove user", err)
}
return ApiSuccess("User removed from organization")
}
开发者ID:wangy1931,项目名称:grafana,代码行数:16,代码来源:org_users.go
注:本文中的github.com/wangy1931/grafana/pkg/bus.Dispatch函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论