本文整理汇总了Golang中github.com/pgpst/pgpst/internal/github.com/dancannon/gorethink.Table函数的典型用法代码示例。如果您正苦于以下问题:Golang Table函数的具体用法?Golang Table怎么用?Golang Table使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Table函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: tokensList
func tokensList(c *cli.Context) int {
// Connect to RethinkDB
_, session, connected := connectToRethinkDB(c)
if !connected {
return 1
}
// Get tokens from database
cursor, err := r.Table("tokens").Map(func(row r.Term) r.Term {
return r.Branch(
row.HasFields("client_id"),
row.Merge(map[string]interface{}{
"owners_address": r.Table("accounts").Get(row.Field("owner")).Field("main_address"),
"client_name": r.Table("applications").Get(row.Field("client_id")).Field("name"),
}),
row.Merge(map[string]interface{}{
"owners_address": r.Table("accounts").Get(row.Field("owner")).Field("main_address"),
}),
)
}).Run(session)
if err != nil {
writeError(c, err)
return 1
}
var tokens []struct {
models.Token
OwnersAddress string `gorethink:"owners_address" json:"owners_address"`
ClientName string `gorethink:"client_name" json:"client_name,omitempty"`
}
if err := cursor.All(&tokens); err != nil {
writeError(c, err)
return 1
}
// Write the output
if c.Bool("json") {
if err := json.NewEncoder(c.App.Writer).Encode(tokens); err != nil {
writeError(c, err)
return 1
}
fmt.Fprint(c.App.Writer, "\n")
} else {
table := termtables.CreateTable()
table.AddHeaders("id", "type", "owner", "client_name", "expired", "date_created")
for _, token := range tokens {
table.AddRow(
token.ID,
token.Type,
token.OwnersAddress,
token.ClientName,
!token.ExpiryDate.IsZero() && token.ExpiryDate.Before(time.Now()),
token.DateCreated.Format(time.RubyDate),
)
}
fmt.Fprintln(c.App.Writer, table.Render())
}
return 0
}
开发者ID:pgpst,项目名称:pgpst,代码行数:60,代码来源:tokens.go
示例2: applicationsList
func applicationsList(c *cli.Context) int {
// Connect to RethinkDB
_, session, connected := connectToRethinkDB(c)
if !connected {
return 1
}
// Get applications from database
cursor, err := r.Table("applications").Map(func(row r.Term) r.Term {
return row.Merge(map[string]interface{}{
"owners_address": r.Table("accounts").Get(row.Field("owner")).Field("main_address"),
})
}).Run(session)
if err != nil {
writeError(c, err)
return 1
}
var applications []struct {
models.Application
OwnersAddress string `gorethink:"owners_address" json:"owners_address"`
}
if err := cursor.All(&applications); err != nil {
writeError(c, err)
return 1
}
// Write the output
if c.Bool("json") {
if err := json.NewEncoder(c.App.Writer).Encode(applications); err != nil {
writeError(c, err)
return 1
}
fmt.Fprint(c.App.Writer, "\n")
} else {
table := termtables.CreateTable()
table.AddHeaders("id", "name", "owner", "homepage", "date_created")
for _, application := range applications {
table.AddRow(
application.ID,
application.Name,
application.OwnersAddress,
application.Homepage,
application.DateCreated.Format(time.RubyDate),
)
}
fmt.Fprintln(c.App.Writer, table.Render())
}
return 0
}
开发者ID:pgpst,项目名称:pgpst,代码行数:51,代码来源:applications.go
示例3: getAccountAddresses
func (a *API) getAccountAddresses(c *gin.Context) {
// Token and account from context
var (
ownAccount = c.MustGet("account").(*models.Account)
token = c.MustGet("token").(*models.Token)
)
// Resolve the ID from the URL
id := c.Param("id")
if id == "me" {
id = ownAccount.ID
}
// Check the scope
if id == ownAccount.ID {
if !models.InScope(token.Scope, []string{"addresses:read"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
} else {
if !models.InScope(token.Scope, []string{"admin"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
}
// Get addresses from database
cursor, err := r.Table("addresses").GetAllByIndex("owner", id).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
defer cursor.Close()
var addresses []*models.Address
if err := cursor.All(&addresses); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
// Write the response
c.JSON(200, addresses)
return
}
开发者ID:pgpst,项目名称:pgpst,代码行数:55,代码来源:routes_addresses.go
示例4: createResource
func (a *API) createResource(c *gin.Context) {
// Get token and account info from the context
var (
account = c.MustGet("account").(*models.Account)
token = c.MustGet("token").(*models.Token)
)
// Check the scope
if !models.InScope(token.Scope, []string{"resources:create"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
// Decode the input
var input struct {
Meta map[string]interface{} `json:"meta"`
Body []byte `json:"body"`
Tags []string `json:"tags"`
}
if err := c.Bind(&input); err != nil {
c.JSON(422, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
// Save it into database
resource := &models.Resource{
ID: uniuri.NewLen(uniuri.UUIDLen),
DateCreated: time.Now(),
DateModified: time.Now(),
Owner: account.ID,
Meta: input.Meta,
Body: input.Body,
Tags: input.Tags,
}
// Insert it into database
if err := r.Table("resources").Insert(resource).Exec(a.Rethink); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
c.JSON(201, resource)
}
开发者ID:pgpst,项目名称:pgpst,代码行数:53,代码来源:routes_resources.go
示例5: readResource
func (a *API) readResource(c *gin.Context) {
// Get token and account info from the context
var (
account = c.MustGet("account").(*models.Account)
token = c.MustGet("token").(*models.Token)
)
// Resolve the resource ID and fetch it from database
id := c.Param("id")
cursor, err := r.Table("resources").Get(id).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
defer cursor.Close()
var resource *models.Resource
if err := cursor.All(&resource); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
if resource.Owner == account.ID {
// Check the scope
if !models.InScope(token.Scope, []string{"resources:read"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
} else {
// Check the scope
if !models.InScope(token.Scope, []string{"admin"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
}
c.JSON(200, resource)
}
开发者ID:pgpst,项目名称:pgpst,代码行数:49,代码来源:routes_resources.go
示例6: accountsAdd
func accountsAdd(c *cli.Context) int {
// Connect to RethinkDB
_, session, connected := connectToRethinkDB(c)
if !connected {
return 1
}
// Input struct
var input struct {
MainAddress string `json:"main_address"`
Password string `json:"password"`
Subscription string `json:"subscription"`
AltEmail string `json:"alt_email"`
Status string `json:"status"`
}
// Read JSON from stdin
if c.Bool("json") {
if err := json.NewDecoder(c.App.Env["reader"].(io.Reader)).Decode(&input); err != nil {
writeError(c, err)
return 1
}
} else {
// Buffer stdin
rd := bufio.NewReader(c.App.Env["reader"].(io.Reader))
var err error
// Acquire from interactive input
fmt.Fprint(c.App.Writer, "Main address: ")
input.MainAddress, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.MainAddress = strings.TrimSpace(input.MainAddress)
fmt.Fprint(c.App.Writer, "Password: ")
input.Password, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Password = strings.TrimSpace(input.Password)
/*password, err := speakeasy.FAsk(rd, "Password: ")
if err != nil {
writeError(c, err)
return 1
}
input.Password = password*/
fmt.Fprint(c.App.Writer, "Subscription [beta/admin]: ")
input.Subscription, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Subscription = strings.TrimSpace(input.Subscription)
fmt.Fprint(c.App.Writer, "Alternative address: ")
input.AltEmail, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.AltEmail = strings.TrimSpace(input.AltEmail)
fmt.Fprint(c.App.Writer, "Status [inactive/active/suspended]: ")
input.Status, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Status = strings.TrimSpace(input.Status)
}
// Analyze the input
// First of all, the address. Append domain if it has no such suffix.
if strings.Index(input.MainAddress, "@") == -1 {
input.MainAddress += "@" + c.GlobalString("default_domain")
}
// And format it
styledID := utils.NormalizeAddress(input.MainAddress)
input.MainAddress = utils.RemoveDots(styledID)
// Then check if it's taken.
cursor, err := r.Table("addresses").Get(input.MainAddress).Ne(nil).Run(session)
if err != nil {
writeError(c, err)
return 1
}
defer cursor.Close()
var taken bool
if err := cursor.One(&taken); err != nil {
writeError(c, err)
return 1
}
if taken {
//.........这里部分代码省略.........
开发者ID:pgpst,项目名称:pgpst,代码行数:101,代码来源:accounts.go
示例7: applicationsAdd
func applicationsAdd(c *cli.Context) int {
// Connect to RethinkDB
_, session, connected := connectToRethinkDB(c)
if !connected {
return 1
}
// Input struct
var input struct {
Owner string `json:"owner"`
Callback string `json:"callback"`
Homepage string `json:"homepage"`
Name string `json:"name"`
Description string `json:"description"`
}
// Read JSON from stdin
if c.Bool("json") {
if err := json.NewDecoder(c.App.Env["reader"].(io.Reader)).Decode(&input); err != nil {
writeError(c, err)
return 1
}
} else {
// Buffer stdin
rd := bufio.NewReader(c.App.Env["reader"].(io.Reader))
var err error
// Acquire from interactive input
fmt.Fprint(c.App.Writer, "Owner's ID: ")
input.Owner, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Owner = strings.TrimSpace(input.Owner)
fmt.Fprint(c.App.Writer, "Application's name: ")
input.Name, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Name = strings.TrimSpace(input.Name)
fmt.Fprint(c.App.Writer, "Homepage URL: ")
input.Homepage, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Homepage = strings.TrimSpace(input.Homepage)
fmt.Fprint(c.App.Writer, "Description: ")
input.Description, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Description = strings.TrimSpace(input.Description)
fmt.Fprint(c.App.Writer, "Callback URL: ")
input.Callback, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Callback = strings.TrimSpace(input.Callback)
}
// Validate the input
// Check if account ID exists
cursor, err := r.Table("accounts").Get(input.Owner).Ne(nil).Run(session)
if err != nil {
writeError(c, err)
return 1
}
defer cursor.Close()
var exists bool
if err := cursor.One(&exists); err != nil {
writeError(c, err)
return 1
}
if !exists {
writeError(c, fmt.Errorf("Account %s doesn't exist", input.Owner))
return 1
}
// Homepage URL should be a URL
if !govalidator.IsURL(input.Homepage) {
writeError(c, fmt.Errorf("%s is not a URL", input.Homepage))
return 1
}
// Callback URL should be a URL
if !govalidator.IsURL(input.Callback) {
writeError(c, fmt.Errorf("%s is not a URL", input.Callback))
return 1
}
//.........这里部分代码省略.........
开发者ID:pgpst,项目名称:pgpst,代码行数:101,代码来源:applications.go
示例8: createKey
//.........这里部分代码省略.........
c.JSON(422, &gin.H{
"code": 0,
"message": "No key body in the input",
})
return
}
// Parse the key
keyring, err := openpgp.ReadKeyRing(bytes.NewReader(input.Body))
if err != nil {
c.JSON(422, &gin.H{
"code": 0,
"message": "Invalid key format",
})
return
}
publicKey := keyring[0].PrimaryKey
// Parse the identities
identities := []*models.Identity{}
for _, identity := range keyring[0].Identities {
id := &models.Identity{
Name: identity.Name,
}
if identity.SelfSignature != nil {
sig := identity.SelfSignature
id.SelfSignature = &models.Signature{
Type: uint8(sig.SigType),
Algorithm: uint8(sig.PubKeyAlgo),
Hash: uint(sig.Hash),
CreationTime: sig.CreationTime,
SigLifetimeSecs: sig.SigLifetimeSecs,
KeyLifetimeSecs: sig.KeyLifetimeSecs,
IssuerKeyID: sig.IssuerKeyId,
IsPrimaryID: sig.IsPrimaryId,
RevocationReason: sig.RevocationReason,
RevocationReasonText: sig.RevocationReasonText,
}
}
if identity.Signatures != nil {
id.Signatures = []*models.Signature{}
for _, sig := range identity.Signatures {
id.Signatures = append(id.Signatures, &models.Signature{
Type: uint8(sig.SigType),
Algorithm: uint8(sig.PubKeyAlgo),
Hash: uint(sig.Hash),
CreationTime: sig.CreationTime,
SigLifetimeSecs: sig.SigLifetimeSecs,
KeyLifetimeSecs: sig.KeyLifetimeSecs,
IssuerKeyID: sig.IssuerKeyId,
IsPrimaryID: sig.IsPrimaryId,
RevocationReason: sig.RevocationReason,
RevocationReasonText: sig.RevocationReasonText,
})
}
}
identities = append(identities, id)
}
// Acquire key's length
length, err := publicKey.BitLength()
if err != nil {
c.JSON(422, &gin.H{
"code": 0,
"message": "Couldn't calculate bit length",
})
return
}
// Generate a new key struct
key := &models.Key{
ID: hex.EncodeToString(publicKey.Fingerprint[:]),
DateCreated: time.Now(),
DateModified: time.Now(),
Owner: account.ID,
Algorithm: uint8(publicKey.PubKeyAlgo),
Length: length,
Body: input.Body,
KeyID: publicKey.KeyId,
KeyIDString: publicKey.KeyIdString(),
KeyIDShortString: publicKey.KeyIdShortString(),
Identities: identities,
}
// Insert it into database
if err := r.Table("keys").Insert(key).Exec(a.Rethink); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
c.JSON(201, key)
}
开发者ID:pgpst,项目名称:pgpst,代码行数:101,代码来源:routes_keys.go
示例9: tokensAdd
func tokensAdd(c *cli.Context) int {
// Connect to RethinkDB
_, session, connected := connectToRethinkDB(c)
if !connected {
return 1
}
// Input struct
var input struct {
Owner string `json:"owner"`
ExpiryDate time.Time `json:"expiry_date"`
Type string `json:"type"`
Scope []string `json:"scope"`
ClientID string `json:"client_id"`
}
// Read JSON from stdin
if c.Bool("json") {
if err := json.NewDecoder(c.App.Env["reader"].(io.Reader)).Decode(&input); err != nil {
writeError(c, err)
return 1
}
} else {
// Buffer stdin
rd := bufio.NewReader(c.App.Env["reader"].(io.Reader))
var err error
// Acquire from interactive input
fmt.Fprint(c.App.Writer, "Owner's ID: ")
input.Owner, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Owner = strings.TrimSpace(input.Owner)
fmt.Fprint(c.App.Writer, "Type [auth/activate/code]: ")
input.Type, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.Type = strings.TrimSpace(input.Type)
fmt.Fprint(c.App.Writer, "Expiry date [2006-01-02T15:04:05Z07:00/empty]: ")
expiryDate, err := rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
expiryDate = strings.TrimSpace(expiryDate)
if expiryDate != "" {
input.ExpiryDate, err = time.Parse(time.RFC3339, expiryDate)
if err != nil {
writeError(c, err)
return 1
}
}
if input.Type == "auth" || input.Type == "code" {
fmt.Fprint(c.App.Writer, "Client ID: ")
input.ClientID, err = rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
input.ClientID = strings.TrimSpace(input.ClientID)
fmt.Fprint(c.App.Writer, "Scope (seperated by commas): ")
scope, err := rd.ReadString('\n')
if err != nil {
writeError(c, err)
return 1
}
scope = strings.TrimSpace(scope)
input.Scope = strings.Split(scope, ",")
}
}
// Validate the input
// Type has to be either auth or activate
if input.Type != "auth" && input.Type != "activate" && input.Type != "code" {
writeError(c, fmt.Errorf("Token type must be either auth or activate. Got %s.", input.Type))
return 1
}
// Scopes must exist
if input.Scope != nil && len(input.Scope) > 0 {
for _, scope := range input.Scope {
if _, ok := models.Scopes[scope]; !ok {
writeError(c, fmt.Errorf("Scope %s doesn't exist", scope))
return 1
}
}
}
// Owner must exist
cursor, err := r.Table("accounts").Get(input.Owner).Ne(nil).Run(session)
if err != nil {
//.........这里部分代码省略.........
开发者ID:pgpst,项目名称:pgpst,代码行数:101,代码来源:tokens.go
示例10: readKey
func (a *API) readKey(c *gin.Context) {
// Resolve the ID param
id := c.Param("id")
if len(id) != 40 {
// Look up by email
cursor, err := r.Table("addresses").Get(id).Default(map[string]interface{}{}).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
defer cursor.Close()
var address *models.Address
if err := cursor.One(&address); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
// Check if we've found that address
if address.ID == "" {
c.JSON(404, &gin.H{
"code": 0,
"message": "Address not found",
})
return
}
// Set the ID accordingly
id = address.PublicKey
}
// Fetch the key from database
cursor, err := r.Table("keys").Get(id).Default(map[string]interface{}{}).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
defer cursor.Close()
var key *models.Key
if err := cursor.One(&key); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
// Ensure that it exists, write the response
if key.ID == "" {
c.JSON(404, &gin.H{
"code": 0,
"message": "Key not found",
})
return
}
c.JSON(200, key)
}
开发者ID:pgpst,项目名称:pgpst,代码行数:65,代码来源:routes_keys.go
示例11: databaseMigrate
func databaseMigrate(c *cli.Context) int {
// Connect to RethinkDB
opts, session, connected := connectToRethinkDB(c)
if !connected {
return 1
}
// Get the migration status from the database
version, err := getDatabaseVersion(opts, session)
if err != nil {
writeError(c, err)
return 1
}
// Show the current migration's status
fmt.Fprintf(c.App.Writer, "Current database schema's version is %d.\n", version)
fmt.Fprintf(c.App.Writer, "Latest migration's version is %d.\n", len(migrations)-1)
// Only proceed if the schema is outdated
if version >= len(migrations)-1 {
fmt.Fprintln(c.App.Writer, "Your schema is up to date.")
return 0
}
// I don't know why would anyone use it, but it's here
if c.Bool("no") {
fmt.Fprintln(c.App.Writer, "Aborting the command because of the --no option.")
return 1
}
// Ask for confirmations
if !c.Bool("yes") {
want, err := utils.AskForConfirmation(
c.App.Writer,
c.App.Env["reader"].(io.Reader),
"Would you like to run "+strconv.Itoa(len(migrations)-1-version)+" migrations? [y/n]: ",
)
if err != nil {
writeError(c, err)
return 1
}
if !want {
fmt.Fprintln(c.App.Writer, "Aborting the command.")
return 1
}
}
// Collect all queries
queries := []r.Term{}
for _, migration := range migrations[version+1:] {
queries = append(queries, migration.Migrate(opts)...)
queries = append(queries, r.Table("migration_status").Get("revision").Update(map[string]interface{}{
"value": migration.Revision,
}))
}
// Create a new progress bar
bar := pb.StartNew(len(queries))
for i, query := range queries {
if c.Bool("dry") {
fmt.Fprintf(c.App.Writer, "Executing %s\n", query.String())
} else {
if err := query.Exec(session); err != nil {
bar.FinishPrint("Failed to execute migration #" + strconv.Itoa(i) + ":")
fmt.Fprintf(c.App.Writer, "\tQuery: %s\n", query.String())
fmt.Fprintf(c.App.Writer, "\tError: %v\n", err)
return 1
}
}
bar.Increment()
}
// Show a "finished" message
bar.FinishPrint("Migration completed. " + strconv.Itoa(len(queries)) + " queries executed.")
return 0
}
开发者ID:pgpst,项目名称:pgpst,代码行数:77,代码来源:database.go
示例12: createAccount
func (a *API) createAccount(c *gin.Context) {
// Decode the input
var input struct {
Action string `json:"action"`
Username string `json:"username"`
AltEmail string `json:"alt_email"`
Token string `json:"token"`
Password string `json:"password"`
Address string `json:"address"`
}
if err := c.Bind(&input); err != nil {
c.JSON(422, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
// Switch the action
switch input.Action {
case "reserve":
// Parameters:
// - username - desired username
// - alt_email - desired email
// Normalize the username
styledID := utils.NormalizeUsername(input.Username)
nu := utils.RemoveDots(styledID)
// Validate input:
// - len(username) >= 3 && len(username) <= 32
// - email.match(alt_email)
errors := []string{}
if len(nu) < 3 {
errors = append(errors, "Username too short. It must be 3-32 characters long.")
}
if len(nu) > 32 {
errors = append(errors, "Username too long. It must be 3-32 characters long.")
}
if !govalidator.IsEmail(input.AltEmail) {
errors = append(errors, "Invalid alternative e-mail format.")
}
if len(errors) > 0 {
c.JSON(422, &gin.H{
"code": 0,
"message": "Validation failed.",
"errors": errors,
})
return
}
// Check in the database whether you can register such account
cursor, err := r.Table("addresses").Get(nu + "@pgp.st").Ne(nil).Do(func(left r.Term) map[string]interface{} {
return map[string]interface{}{
"username": left,
"alt_email": r.Table("accounts").GetAllByIndex("alt_email", input.AltEmail).Count().Eq(1),
}
}).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
defer cursor.Close()
var result struct {
Username bool `gorethink:"username"`
AltEmail bool `gorethink:"alt_email"`
}
if err := cursor.One(&result); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
if result.Username || result.AltEmail {
errors := []string{}
if result.Username {
errors = append(errors, "This username is taken.")
}
if result.AltEmail {
errors = append(errors, "This email address is used.")
}
c.JSON(422, &gin.H{
"code": 0,
"message": "Naming conflict",
"errors": errors,
})
return
}
// Create an account and an address
address := &models.Address{
ID: nu + "@pgp.st",
StyledID: styledID + "@pgp.st",
DateCreated: time.Now(),
Owner: "", // we set it later
}
//.........这里部分代码省略.........
开发者ID:pgpst,项目名称:pgpst,代码行数:101,代码来源:routes_accounts.go
示例13: HandleDelivery
//.........这里部分代码省略.........
return
}
encryptedManifest, err := utils.PGPEncrypt(manifest, keyring)
if err != nil {
m.Error(conn, err)
return
}
email.Manifest = encryptedManifest
// Match the thread
var thread *models.Thread
// Get the References header
var references string
if x := node.Headers.Get("In-Reply-To"); x != "" {
references = x
} else if x := node.Headers.Get("References"); x != "" {
references = x
}
// Match by Message-ID
if references != "" {
// As specified in http://www.jwz.org/doc/threading.html, first thing <> is the msg id
// We support both <message-id> and message-id format.
x1i := strings.Index(references, "<")
if x1i != -1 {
x2i := strings.Index(references[x1i+1:], ">")
if x2i != -1 {
references = references[x1i+1 : x1i+x2i+1]
}
}
// Look up the message ID in the database
cursor, err := r.Table("emails").GetAllByIndex("messageIDOwner", []interface{}{
references,
recipient.Account.ID,
}).CoerceTo("array").Do(func(emails r.Term) r.Term {
return r.Branch(
emails.Count().Eq(1),
r.Table("threads").Get(emails.Nth(0).Field("thread")).Default(map[string]interface{}{}),
map[string]interface{}{},
)
}).Run(m.Rethink)
if err != nil {
m.Error(conn, err)
return
}
defer cursor.Close()
if err := cursor.One(&thread); err != nil {
m.Error(conn, err)
return
}
// Check if we've found it, clear it if it's invalid
if thread.ID == "" {
thread = nil
}
}
// We can't match it by subject, so proceed to create a new thread
if thread == nil {
var secure string
if findEncrypted(node) {
secure = "all"
} else {
secure = "none"
开发者ID:pgpst,项目名称:pgpst,代码行数:67,代码来源:handler.go
示例14: oauthToken
func (a *API) oauthToken(c *gin.Context) {
// Decode the input
var input struct {
GrantType string `json:"grant_type"`
Code string `json:"code"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Address string `json:"address"`
Password string `json:"password"`
ExpiryTime int64 `json:"expiry_time"`
}
if err := c.Bind(&input); err != nil {
c.JSON(422, &gin.H{
"code": CodeGeneralInvalidInput,
"message": err.Error(),
})
return
}
// Switch the action
switch input.GrantType {
case "authorization_code":
// Parameters:
// - code - authorization code from the app
// - client_id - id of the client app
// - client_secret - secret of the client app
// Fetch the application from database
cursor, err := r.Table("applications").Get(input.ClientID).Default(map[string]interface{}{}).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": CodeGeneralDatabaseError,
"message": err.Error(),
})
return
}
defer cursor.Close()
var application *models.Application
if err := cursor.One(&application); err != nil {
c.JSON(500, &gin.H{
"code": CodeGeneralDatabaseError,
"message": err.Error(),
})
return
}
if application.ID == "" {
c.JSON(422, &gin.H{
"code": CodeOAuthInvalidApplication,
"message": "No such client ID.",
})
return
}
if application.Secret != input.ClientSecret {
c.JSON(422, &gin.H{
"code": CodeOAuthInvalidSecret,
"message": "Invalid client secret.",
})
return
}
// Fetch the code from the database
cursor, err = r.Table("tokens").Get(input.Code).Default(map[string]interface{}{}).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": CodeGeneralDatabaseError,
"message": err.Error(),
})
return
}
defer cursor.Close()
var codeToken *models.Token
if err := cursor.One(&codeToken); err != nil {
c.JSON(500, &gin.H{
"code": CodeGeneralDatabaseError,
"message": err.Error(),
})
return
}
// Ensure token type and matching client id
if codeToken.ID == "" || codeToken.Type != "code" || codeToken.ClientID != input.ClientID {
c.JSON(422, &gin.H{
"code": CodeOAuthInvalidCode,
"message": "Invalid code",
})
return
}
// Create a new authentication code
token := &models.Token{
ID: uniuri.NewLen(uniuri.UUIDLen),
DateCreated: time.Now(),
DateModified: time.Now(),
Owner: codeToken.Owner,
ExpiryDate: codeToken.ExpiryDate,
Type: "auth",
Scope: codeToken.Scope,
ClientID: input.ClientID,
}
//.........这里部分代码省略.........
开发者ID:pgpst,项目名称:pgpst,代码行数:101,代码来源:routes_oauth.go
示例15: getAccountResources
func (a *API) getAccountResources(c *gin.Context) {
// Token and account from context
var (
ownAccount = c.MustGet("account").(*models.Account)
token = c.MustGet("token").(*models.Token)
)
// Resolve the ID from the URL
id := c.Param("id")
if id == "me" {
id = ownAccount.ID
}
// Check the scope
if id == ownAccount.ID {
if !models.InScope(token.Scope, []string{"resources:read"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
} else {
if !models.InScope(token.Scope, []string{"admin"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
}
// 1. Owner filter
query := r.Table("resources").GetAllByIndex("owner", id)
// 2. Tag filter
if tagstr := c.Query("tags"); tagstr != "" {
tags := strings.Split(tagstr, ",")
// Cast to []interface{}
tagsi := []interface{}{}
for _, tag := range tags {
tagsi = append(tagsi, tag)
}
query = query.Filter(func(row r.Term) r.Term {
return row.Field("tags").Contains(tagsi...)
})
}
// 3. Meta filter
// not needed right now
// 4. Date created and date modified
ts := func(field string) error {
if dm := c.Query(field); dm != "" {
dmp := strings.Split(dm, ",")
if len(dmp) == 1 || dmp[1] == "" {
// parse dmp[0]
d0, err := time.Parse(time.RFC3339, dmp[0])
if err != nil {
return err
}
// after dmp[0]
query = query.Filter(func(row r.Term) r.Term {
return row.Field(field).Ge(d0)
})
} else {
// parse dmp[1]
d1, err := time.Parse(time.RFC3339, dmp[1])
if err != nil {
return err
}
if dmp[0] == "" {
// until dmp[1]
query = query.Filter(func(row r.Term) r.Term {
return row.Field(field).Le(d1)
})
} else {
// parse dmp[0]
d0, err := time.Parse(time.RFC3339, dmp[0])
if err != nil {
return err
}
// between dmp[0] and dmp[1]
query = query.Filter(func(row r.Term) r.Term {
return row.Field(field).Ge(d0).And(row.Field(field).Le(d1))
})
}
}
}
return nil
}
if err := ts("date_modified"); err != nil {
c.JSON(500, &gin.H{
"code": 0,
//.........这里部分代码省略.........
开发者ID:pgpst,项目名称:pgpst,代码行数:101,代码来源:routes_resources.go
示例16: getAccountLabels
func (a *API) getAccountLabels(c *gin.Context) {
// Token and account from context
var (
ownAccount = c.MustGet("account").(*models.Account)
token = c.MustGet("token").(*models.Token)
)
// Resolve the ID from the URL
id := c.Param("id")
if id == "me" {
id = ownAccount.ID
}
// Check the scope
if id == ownAccount.ID {
if !models.InScope(token.Scope, []string{"labels:read"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
} else {
if !models.InScope(token.Scope, []string{"admin"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
}
// Get labels from database
cursor, err := r.Table("labels").GetAllByIndex("owner", id).Map(func(label r.Term) r.Term {
return label.Merge(map[string]interface{}{
"total_threads": r.Table("threads").GetAllByIndex("labels", label.Field("id")).Count(),
"unread_threads": r.Table("threads").GetAllByIndex("labelsIsRead", []interface{}{
label.Field("id"),
false,
}).Count(),
})
}).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
defer cursor.Close()
var labels []struct {
models.Label
TotalThreads int `json:"total_threads" gorethink:"total_threads"`
UnreadThreads int `json:"unread_threads" gorethink:"unread_threads"`
}
if err := cursor.All(&labels); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
// Write the response
c.JSON(200, labels)
return
}
开发者ID:pgpst,项目名称:pgpst,代码行数:67,代码来源:routes_labels.go
示例17: getLabelThreads
func (a *API) getLabelThreads(c *gin.Context) {
// Token and account from context
var (
account = c.MustGet("account").(*models.Account)
token = c.MustGet("token").(*models.Token)
)
// Resolve the ID from the URL
id := c.Param("id")
// Get label from the database
cursor, err := r.Table("labels").Get(id).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
var label *models.Label
if err := cursor.One(&label); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
// Check the ownership and scope
if label.Owner == account.ID {
if !models.InScope(token.Scope, []string{"labels:read"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
} else {
if !models.InScope(token.Scope, []string{"admin"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
}
// Get threads from the database
cursor, err = r.Table("threads").GetAllByIndex("labels", label.ID).OrderBy(r.Desc("date_modified")).Map(func(thread r.Term) r.Term {
return thread.Merge(map[string]interface{}{
"manifest": r.Table("emails").GetAllByIndex("thread", thread.Field("id")).OrderBy("date_modified").CoerceTo("array"),
}).Do(func(thread r.Term) r.Term {
return r.Branch(
thread.Field("manifest").Count().Gt(0),
thread.Merge(map[string]interface{}{
"manifest": thread.Field("manifest").Nth(0).Field("manifest"),
}),
thread.Without("manifest"),
)
})
}).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
var threads []*extendedThread
if err := cursor.All(&threads); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"error": err.Error(),
})
return
}
if threads == nil {
threads = []*extendedThread{}
}
// Write the response
c.JSON(200, threads)
return
}
开发者ID:pgpst,项目名称:pgpst,代码行数:84,代码来源:routes_threads.go
示例18: updateAccount
func (a *API) updateAccount(c *gin.Context) {
// Get token and account info from the context
var (
account = c.MustGet("account").(*models.Account)
token = c.MustGet("token").(*models.Token)
)
// Decode the input
var input struct {
MainAddress string `json:"main_address"`
NewPassword []byte `json:"new_password"`
OldPassword []byte `json:"old_password"`
}
if err := c.Bind(&input); err != nil {
c.JSON(422, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
var newAddress *models.Address
if input.MainAddress != "" {
// Fetch address from the database
cursor, err := r.Table("addresses").Get(input.MainAddress).Default(map[string]interface{}{}).Run(a.Rethink)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
defer cursor.Close()
if err := cursor.One(&newAddress); err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
// Verify that we got something
if newAddress.ID == "" {
c.JSON(422, &gin.H{
"code": 0,
"message": "No such address exists",
})
return
}
}
// Resolve the account ID and check scope accordingly
id := c.Param("id")
if id == "me" {
// Swap the ID to own account's ID
id = account.ID
}
if id == account.ID {
// Check the scope
if !models.InScope(token.Scope, []string{"account:modify"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
// Validate password
valid, _, err := account.VerifyPassword(input.OldPassword)
if err != nil {
c.JSON(500, &gin.H{
"code": 0,
"message": err.Error(),
})
return
}
if !valid {
c.JSON(401, &gin.H{
"code": 0,
"message": "Invalid password",
})
return
}
} else {
// Check the scope
if !models.InScope(token.Scope, []string{"admin"}) {
c.JSON(403, &gin.H{
"code": 0,
"error": "Your token has insufficient scope",
})
return
}
// Fetch the account from the database
cursor, err := r.Table("accounts").Get(id).Default(map[string]interface{}{}).Run(a.Rethink)
if err != n
|
请发表评论