示例#1
0
func PreAuthRequest(ctx context.Context) {
	id := ctx.PathValue("id")
	if p, err := preauth.Load(id); err != nil {
		err_msg := "err:@preAuth load: " + err.Error()
		logger.Error(err_msg)
		responder.RespondWithError(ctx, 500, err_msg)
		return
	} else {
		if n, err := node.LoadUnauth(p.NodeId); err == nil {
			switch p.Type {
			case "download":
				filename := n.Id
				if fn, has := p.Options["filename"]; has {
					filename = fn
				}
				streamDownload(ctx, n, filename)
				preauth.Delete(id)
				return
			default:
				responder.RespondWithError(ctx, 500, "Preauthorization type not supported: "+p.Type)
			}
		} else {
			err_msg := "err:@preAuth loadnode: " + err.Error()
			logger.Error(err_msg)
			responder.RespondWithError(ctx, 500, err_msg)
		}
	}
	return
}
示例#2
0
func (c *AccountTransactions) Create(ctx context.Context) (err error) {
	accountId := ctx.PathValue("account_id")
	data, err := ctx.RequestData()

	if err != nil {
		return goweb.API.RespondWithError(ctx, http.StatusInternalServerError, err.Error())
	}

	dataMap := data.(map[string]interface{})

	transaction := models.Transaction{
		AccountId: accountId,
		Debit:     dataMap["debit"].(float64),
		Credit:    dataMap["credit"].(float64),
		Kind:      dataMap["kind"].(string),
	}

	createServ := &transactions.CreateServ{}
	transactionOut, err := createServ.Run(c.DbSession, transaction)
	if err != nil {
		log.Print(err)
		return goweb.API.RespondWithError(ctx, http.StatusInternalServerError, err.Error())
	}

	return goweb.API.RespondWithData(ctx, transactionOut)
}
示例#3
0
func nuttyGetLength(c context.Context) error {
	sessionid := c.PathValue("sessionid")
	bs, err := ioutil.ReadFile(basedir + sessionid + "/rec.json")
	if err != nil {
		log.Println(err)
		return goweb.API.RespondWithError(c, http.StatusInternalServerError, "Unable to ReadFile")
	}
	return goweb.Respond.With(c, 200, bs)
}
示例#4
0
func nuttyGet(c context.Context) error {
	sessionid := c.PathValue("sessionid")
	tindex := c.PathValue("tindex")

	log.Println("GET ", sessionid, " ", tindex)

	bs, err := ioutil.ReadFile(basedir + sessionid + "/" + tindex)
	if err != nil {
		log.Println(err)
		return goweb.API.RespondWithError(c, http.StatusInternalServerError, "Unable to ReadFile")
	}
	return goweb.Respond.With(c, 200, bs)
}
示例#5
0
文件: acl.go 项目: narayandesai/Shock
// GET, POST, PUT, DELETE: /node/{nid}/acl/
// GET is the only action implemented here.
func AclRequest(ctx context.Context) {
	nid := ctx.PathValue("nid")

	u, err := request.Authenticate(ctx.HttpRequest())
	if err != nil && err.Error() != e.NoAuth {
		request.AuthError(err, ctx)
		return
	}

	// acl require auth even for public data
	if u == nil {
		responder.RespondWithError(ctx, http.StatusUnauthorized, e.NoAuth)
		return
	}

	// Load node and handle user unauthorized
	n, err := node.Load(nid, u.Uuid)
	if err != nil {
		if err.Error() == e.UnAuth {
			responder.RespondWithError(ctx, http.StatusUnauthorized, e.UnAuth)
			return
		} else if err.Error() == e.MongoDocNotFound {
			responder.RespondWithError(ctx, http.StatusNotFound, "Node not found")
			return
		} else {
			// In theory the db connection could be lost between
			// checking user and load but seems unlikely.
			err_msg := "Err@node_Read:LoadNode: " + err.Error()
			logger.Error(err_msg)
			responder.RespondWithError(ctx, http.StatusInternalServerError, err_msg)
			return
		}
	}

	rights := n.Acl.Check(u.Uuid)
	if ctx.HttpRequest().Method == "GET" {
		if u.Uuid == n.Acl.Owner || rights["read"] {
			responder.RespondWithData(ctx, n.Acl)
		} else {
			responder.RespondWithError(ctx, http.StatusUnauthorized, e.UnAuth)
			return
		}
	} else {
		responder.RespondWithError(ctx, http.StatusNotImplemented, "This request type is not implemented.")
	}
	return
}
示例#6
0
文件: endpoints.go 项目: catanm/gms
func Connect(ctx context.Context) error {
	provider_type := ctx.PathValue("provider")
	action := ctx.PathValue("action")

	if provider_type == "facebook" {
		provider, err := gomniauth.Provider(provider_type)
		if err != nil {
			log.Error("Error on getting provider: " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."})
		}
		state := gomniauth.NewState("after", "success")
		// if you want to request additional scopes from the provider,
		// pass them as login?scope=scope1,scope2
		//options := objx.MSI("scope", ctx.QueryValue("scope"))
		authUrl, err := provider.GetBeginAuthURL(state, nil)
		if err != nil {
			log.Error("Error on getting url: " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."})
		}
		// redirect
		return goweb.Respond.WithRedirect(ctx, authUrl)
	} else if provider_type == "local" && ctx.MethodString() == "POST" {
		// This is taken care of in separate functions.
		// Local login only with POST
		if action == "login" {
			return nil
		} else if action == "register" {
			return nil
		} else if action == "connect" {
			return nil
		} else {
			return goweb.API.Respond(ctx, 200, nil, []string{"Invalid action."})
		}
	} else {
		return goweb.API.Respond(ctx, 200, nil, []string{"Invalid provider type."})
	}
}
示例#7
0
func nuttyPut(c context.Context) error {
	sessionid := c.PathValue("sessionid")
	tindex := c.PathValue("tindex")

	log.Println("PUT ", sessionid, " ", tindex)

	data, dataErr := c.RequestBody()
	if dataErr != nil {
		log.Println(dataErr)
		return goweb.API.RespondWithError(c, http.StatusInternalServerError, dataErr.Error())
	}
	dataErr = os.MkdirAll(basedir+sessionid, 0700)
	if dataErr != nil {
		log.Println(dataErr)
		return goweb.API.RespondWithError(c, http.StatusInternalServerError, "Unable to create directory")
	}
	dataErr = ioutil.WriteFile(basedir+sessionid+"/"+tindex, data, 0600)
	if dataErr != nil {
		log.Println(dataErr)
		return goweb.API.RespondWithError(c, http.StatusInternalServerError, "Unable to WriteFile")
	}
	rjsonBytes, err := json.Marshal(struct {
		tindex string `json:"end"`
	}{
		tindex: tindex,
	})
	if err != nil {
		log.Fatalln(err)
	}
	dataErr = ioutil.WriteFile(basedir+sessionid+"/rec.json", rjsonBytes, 0600)
	if dataErr != nil {
		log.Println(dataErr)
		return goweb.API.RespondWithError(c, http.StatusInternalServerError, "Unable to WriteFile")
	}
	return goweb.API.Respond(c, 200, nil, nil)
}
示例#8
0
func (c *AccountTransactions) ReadMany(ctx context.Context) (err error) {

	var transactions []models.Transaction
	accountId := ctx.PathValue("account_id")

	rows, err := r.Table("transactions").Filter(r.Row.Field("accountId").Eq(accountId)).OrderBy(r.Desc("createdAt")).Run(c.DbSession)

	for rows.Next() {
		var transaction models.Transaction

		err = rows.Scan(&transaction)
		if err != nil {
			return
		}

		transactions = append(transactions, transaction)
	}

	if err != nil {
		log.Fatal(err)
		return goweb.Respond.WithStatus(ctx, http.StatusNotFound)
	}
	return goweb.API.RespondWithData(ctx, transactions)
}
示例#9
0
文件: endpoints.go 项目: catanm/gms
func Callback(ctx context.Context) error {
	provider_type := ctx.PathValue("provider")
	provider, err := gomniauth.Provider(provider_type)
	if err != nil {
		log.Error("Error on getting provider: " + err.Error())
		return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."})
	}
	creds, err := provider.CompleteAuth(ctx.QueryParams())
	if err != nil {
		log.Error("Error on completing auth: " + err.Error())
		return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."})
	}
	// load the user
	// https://github.com/stretchr/gomniauth/blob/master/common/user.go
	user, userErr := provider.GetUser(creds)
	if userErr != nil {
		log.Error("Error on getting user: "******"An error has occured."})
	}

	passport := m.Passport{}
	err = m.GetDB("Passport").
		Find(bson.M{"provider": provider_type,
			"identifier": user.IDForProvider(provider_type)}).
		One(&passport)
	if err != nil {
		if err.Error() == "not found" {
			var currentUser, ok = ctx.Data()["user"].(m.User)
			if ok {
				err = m.GetDB("Passport").
					Insert(&m.Passport{bson.NewObjectId(), currentUser.Id, "", provider_type,
						user.IDForProvider(provider_type), fmt.Sprintf("%v", creds.Map.Get("access_token").Data()),
						fmt.Sprintf("%v", creds.Map.Get("refresh_token").Data())})
				if err != nil {
					log.Error("Error on registration with provider " + provider_type + ", new passport: " + err.Error())
					return goweb.API.Respond(ctx, 200, nil, []string{"Could not create your new authorization."})
				}
				log.Info("Connecting user")
				url, _ := url.Parse(utils.EnvUrl() + "/#/fblogin/?token=" + currentUser.Token)
				return goweb.Respond.WithRedirect(ctx, url)
			} else {
				// No user, create user, create passport
				var token = nonce.NewToken()
				nonce.MarkToken(token)
				newUser := m.User{bson.NewObjectId(), user.Nickname(), user.Email(), true, token, time.Now()}
				err = m.GetDB("User").Insert(&newUser)
				if err != nil {
					log.Error("Error on registration with provider " + provider_type + ", new user: "******"Failed to register."})
				}
				err = m.GetDB("Passport").
					Insert(&m.Passport{bson.NewObjectId(), newUser.Id, "", provider_type,
						user.IDForProvider(provider_type), fmt.Sprintf("%v", creds.Map.Get("access_token").Data()),
						fmt.Sprintf("%v", creds.Map.Get("refresh_token").Data())})
				if err != nil {
					log.Error("Error on registration with provider " + provider_type + ", new user passport: " + err.Error())
					return goweb.API.Respond(ctx, 200, nil, []string{"Failed to create your new passport."})
				}
				log.Info("New user registered")
				url, _ := url.Parse(utils.EnvUrl() + "/#/fblogin/?token=" + newUser.Token)
				return goweb.Respond.WithRedirect(ctx, url)
			}
		} else {
			log.Error("Error on registration with provider " + provider_type + ", new passport: " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"Could not find your authorization."})
		}
	} else {
		// login the user
		var user = m.User{}
		fmt.Println(passport)
		err = m.GetDB("User").Find(bson.M{"_id": passport.User}).One(&user)
		if err != nil {
			log.Error("Error on login with provider " + provider_type + ", user query: " + err.Error())
			return goweb.API.Respond(ctx, 200, nil, []string{"Could not find you on the database."})
		}
		log.Info("Found user returning id")
		url, _ := url.Parse(utils.EnvUrl() + "/#/fblogin/?token=" + user.Token)
		return goweb.Respond.WithRedirect(ctx, url)
	}
}
示例#10
0
文件: acl.go 项目: narayandesai/Shock
// GET, POST, PUT, DELETE: /node/{nid}/acl/{type}
func AclTypedRequest(ctx context.Context) {
	nid := ctx.PathValue("nid")
	rtype := ctx.PathValue("type")

	u, err := request.Authenticate(ctx.HttpRequest())
	if err != nil && err.Error() != e.NoAuth {
		request.AuthError(err, ctx)
		return
	}

	// acl require auth even for public data
	if u == nil {
		responder.RespondWithError(ctx, http.StatusUnauthorized, e.NoAuth)
		return
	}

	if !validAclTypes[rtype] {
		responder.RespondWithError(ctx, http.StatusBadRequest, "Invalid acl type")
		return
	}

	// Load node and handle user unauthorized
	n, err := node.Load(nid, u.Uuid)
	if err != nil {
		if err.Error() == e.UnAuth {
			responder.RespondWithError(ctx, http.StatusUnauthorized, e.UnAuth)
			return
		} else if err.Error() == e.MongoDocNotFound {
			responder.RespondWithError(ctx, http.StatusNotFound, "Node not found")
			return
		} else {
			// In theory the db connection could be lost between
			// checking user and load but seems unlikely.
			err_msg := "Err@node_Read:LoadNode: " + err.Error()
			logger.Error(err_msg)
			responder.RespondWithError(ctx, http.StatusInternalServerError, err_msg)
			return
		}
	}

	rights := n.Acl.Check(u.Uuid)
	requestMethod := ctx.HttpRequest().Method
	if requestMethod != "GET" {
		ids, err := parseAclRequestTyped(ctx)
		if err != nil {
			responder.RespondWithError(ctx, http.StatusBadRequest, err.Error())
			return
		}
		if (requestMethod == "POST" || requestMethod == "PUT") && (u.Uuid == n.Acl.Owner || rights["write"]) {
			if rtype == "owner" {
				if u.Uuid == n.Acl.Owner {
					if len(ids) == 1 {
						n.Acl.SetOwner(ids[0])
					} else {
						responder.RespondWithError(ctx, http.StatusBadRequest, "Too many users. Nodes may have only one owner.")
						return
					}
				} else {
					responder.RespondWithError(ctx, http.StatusBadRequest, "Only owner can change ownership of Node.")
					return
				}
			} else if rtype == "all" {
				for _, atype := range []string{"read", "write", "delete"} {
					for _, i := range ids {
						n.Acl.Set(i, map[string]bool{atype: true})
					}
				}
			} else {
				for _, i := range ids {
					n.Acl.Set(i, map[string]bool{rtype: true})
				}
			}
			n.Save()
		} else if requestMethod == "DELETE" && (u.Uuid == n.Acl.Owner || rights["delete"]) {
			if rtype == "owner" {
				responder.RespondWithError(ctx, http.StatusBadRequest, "Deleting ownership is not a supported request type.")
				return
			} else if rtype == "all" {
				for _, atype := range []string{"read", "write", "delete"} {
					for _, i := range ids {
						n.Acl.UnSet(i, map[string]bool{atype: true})
					}
				}
			} else {
				for _, i := range ids {
					n.Acl.UnSet(i, map[string]bool{rtype: true})
				}
			}
			n.Save()
		} else {
			responder.RespondWithError(ctx, http.StatusUnauthorized, e.UnAuth)
			return
		}
	}

	if u.Uuid == n.Acl.Owner || rights["read"] {
		switch rtype {
		case "read":
			responder.RespondWithData(ctx, map[string][]string{"read": n.Acl.Read})
		case "write":
			responder.RespondWithData(ctx, map[string][]string{"write": n.Acl.Write})
		case "delete":
			responder.RespondWithData(ctx, map[string][]string{"delete": n.Acl.Delete})
		case "owner":
			responder.RespondWithData(ctx, map[string]string{"owner": n.Acl.Owner})
		case "all":
			responder.RespondWithData(ctx, n.Acl)
		}
	} else {
		responder.RespondWithError(ctx, http.StatusUnauthorized, e.UnAuth)
		return
	}
	return
}