util.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package fire
  2. import (
  3. "context"
  4. "errors"
  5. "strings"
  6. "time"
  7. "cloud.google.com/go/firestore"
  8. firebase "firebase.google.com/go"
  9. )
  10. // getContextValue returns value of the specified key from context
  11. func getContextValue(ctx context.Context, key string) (string, bool) {
  12. value, ok := ctx.Value(key).(string)
  13. return value, ok
  14. }
  15. // ColRef returns collection reference
  16. func ColRef(client *firestore.Client, names ...string) *firestore.CollectionRef {
  17. path := strings.Join(names, "/")
  18. return client.Collection(path)
  19. }
  20. // DocRef returns document reference
  21. func DocRef(client *firestore.Client, names ...string) *firestore.DocumentRef {
  22. path := strings.Join(names, "/")
  23. return client.Doc(path)
  24. }
  25. // NowMM returns now time of Myanmar Timezone
  26. func NowMM() (*time.Time, error) {
  27. loc, err := time.LoadLocation("Asia/Rangoon")
  28. if err != nil {
  29. return nil, err
  30. }
  31. //set timezone,
  32. now := time.Now().In(loc)
  33. return &now, nil
  34. }
  35. // TimestampMilli returns time in milli seconds
  36. func TimestampMilli(t time.Time) int64 {
  37. return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
  38. }
  39. func getDocWithID(ctx context.Context, ref *firestore.DocumentRef) (map[string]interface{}, error) {
  40. snap, err := ref.Get(ctx)
  41. if err != nil {
  42. return nil, err
  43. }
  44. doc := snap.Data()
  45. doc["id"] = snap.Ref.ID
  46. return doc, nil
  47. }
  48. // SetClaim set claims to user
  49. func SetClaim(ctx context.Context, app *firebase.App, phoneNumber string, claims map[string]interface{}) error {
  50. client, err := app.Auth(ctx)
  51. if err != nil {
  52. return errors.New("error getting Auth client: " + err.Error())
  53. }
  54. user, err := client.GetUserByPhoneNumber(ctx, phoneNumber)
  55. if err != nil {
  56. return errors.New("error getting user by phone: " + err.Error())
  57. }
  58. _claims := make(map[string]interface{})
  59. for k, v := range user.CustomClaims {
  60. _claims[k] = v
  61. }
  62. for k, v := range claims {
  63. _claims[k] = v
  64. }
  65. // fmt.Println("all claims:", _claims)
  66. err = client.SetCustomUserClaims(ctx, user.UID, _claims)
  67. if err != nil {
  68. return errors.New("error set customer claim: " + err.Error())
  69. }
  70. return nil
  71. }