Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

basic fb auth working

goenning12e2294d960f
diff --git a/auth/service.go b/auth/service.go
new file mode 100644
index 000000000..941900421
--- /dev/null
+++ b/auth/service.go
@@ -0,0 +1,66 @@
+package auth
+
+import (
+ "database/sql"
+ "errors"
+)
+
+var (
+ OAUTH_FACEBOOK_PROVIDER = "facebook"
+)
+
+//User represents an user inside our application
+type User struct {
+ ID int
+ Name string
+ Email string
+ Providers []*UserProvider
+}
+
+//UserProvider represents the relashionship between an User and an Authentication provide
+type UserProvider struct {
+ Name string
+ UID string
+}
+
+//ErrUserNotFound is "User not found"
+var ErrUserNotFound = errors.New("User not found")
+
+// Service is used for auth operations
+type Service interface {
+ GetByEmail(email string) (*User, error)
+ Register(user *User) error
+}
+
+// PostgresService is used for auth operations using a Postgres database
+type PostgresService struct {
+ DB *sql.DB
+}
+
+// GetByEmail returns a user based on given email
+func (svc PostgresService) GetByEmail(email string) (*User, error) {
+ user := &User{}
+ row := svc.DB.QueryRow("SELECT id, name, email FROM users WHERE email = $1", email)
+ err := row.Scan(&user.ID, &user.Name, &user.Email)
+ if err != nil {
+ return nil, ErrUserNotFound
+ }
+
+ return user, nil
+}
+
+// Register creates a new user based on given information
+func (svc PostgresService) Register(user *User) error {
+ row := svc.DB.QueryRow("INSERT INTO users (name, email) VALUES($1, $2) returning id;", user.Name, user.Email)
+ err := row.Scan(&user.ID)
+ if err != nil {
+ return err
+ }
+
+ err = svc.DB.QueryRow("INSERT INTO user_providers (user_id, provider, provider_uid) VALUES($1, $2, $3);", user.ID, user.Providers[0].Name, user.Providers[0].UID).Scan()
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/context/wchy.go b/context/wchy.go
index a370d84da..15ef2352a 100644
--- a/context/wchy.go
+++ b/context/wchy.go
@@ -1,6 +1,9 @@
package context
-import "github.com/WeCanHearYou/wchy/service"
+import (
+ "github.com/WeCanHearYou/wchy/auth"
+ "github.com/WeCanHearYou/wchy/service"
+)
// WchySettings is an application-wide settings
type WchySettings struct {
@@ -11,6 +14,7 @@ type WchySettings struct {
// WchyContext is an application-wide context
type WchyContext struct {
Health service.HealthCheckService
+ Auth auth.Service
Idea service.IdeaService
Tenant service.TenantService
Settings WchySettings
diff --git a/handler/oauth.go b/handler/oauth.go
index f161c0503..6d60f740c 100644
--- a/handler/oauth.go
+++ b/handler/oauth.go
@@ -1,8 +1,8 @@
package handler
import (
+ "encoding/json"
"io/ioutil"
- "log"
"net/http"
"net/url"
"os"
@@ -11,10 +11,17 @@ import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/facebook"
+ "github.com/WeCanHearYou/wchy/auth"
"github.com/WeCanHearYou/wchy/context"
"github.com/labstack/echo"
)
+type facebookUser struct {
+ Name string
+ ID string
+ Email string
+}
+
var (
oauthState = os.Getenv("OAUTH_STATE")
)
@@ -23,7 +30,7 @@ func newFacebookOAuthConfig(redirect string) *oauth2.Config {
return &oauth2.Config{
ClientID: os.Getenv("OAUTH_FACEBOOK_APPID"),
ClientSecret: os.Getenv("OAUTH_FACEBOOK_SECRET"),
- RedirectURL: os.Getenv("AUTH_ENDPOINT") + "/oauth/callback?redirect=" + url.QueryEscape(redirect),
+ RedirectURL: os.Getenv("AUTH_ENDPOINT") + "/oauth/facebook/callback?redirect=" + url.QueryEscape(redirect),
Scopes: []string{"public_profile", "email"},
Endpoint: facebook.Endpoint,
}
@@ -58,10 +65,34 @@ func (h OAuthHandlers) Callback() echo.HandlerFunc {
return c.Redirect(http.StatusTemporaryRedirect, redirect) //TODO: redirect to some error page
}
- resp, err := http.Get("https://graph.facebook.com/me?fields=name,email&access_token=" + url.QueryEscape(token.AccessToken))
- defer resp.Body.Close()
- response, err := ioutil.ReadAll(resp.Body)
- log.Printf("parseResponseBody: %s\n", string(response))
+ r, err := http.Get("https://graph.facebook.com/me?fields=name,email&access_token=" + url.QueryEscape(token.AccessToken))
+ defer r.Body.Close()
+
+ fbUser := &facebookUser{}
+ bytes, err := ioutil.ReadAll(r.Body)
+ err = json.Unmarshal(bytes, fbUser)
+
+ user, err := h.ctx.Auth.GetByEmail(fbUser.Email)
+ if err != nil {
+ if err == auth.ErrUserNotFound {
+ user := &auth.User{
+ Name: fbUser.Name,
+ Email: fbUser.Email,
+ Providers: []*auth.UserProvider{
+ &auth.UserProvider{
+ UID: fbUser.ID,
+ Name: auth.OAUTH_FACEBOOK_PROVIDER,
+ },
+ },
+ }
+ err = h.ctx.Auth.Register(user)
+ if err != nil {
+ c.Logger().Error(err)
+ }
+ }
+ }
+
+ c.Logger().Infof("Logged in as %s", user)
return c.Redirect(http.StatusTemporaryRedirect, redirect)
}
diff --git a/main.go b/main.go
index ea48ee765..396ce4b30 100644
--- a/main.go
+++ b/main.go
@@ -7,6 +7,7 @@ import (
"fmt"
+ "github.com/WeCanHearYou/wchy/auth"
"github.com/WeCanHearYou/wchy/context"
"github.com/WeCanHearYou/wchy/env"
"github.com/WeCanHearYou/wchy/router"
@@ -31,6 +32,7 @@ func init() {
ctx = &context.WchyContext{
Health: &service.PostgresHealthCheckService{DB: db},
Idea: &service.PostgresIdeaService{DB: db},
+ Auth: &auth.PostgresService{DB: db},
Tenant: &service.PostgresTenantService{DB: db},
Settings: context.WchySettings{
BuildTime: buildtime,
diff --git a/router/router.go b/router/router.go
index c51942cc8..257099997 100644
--- a/router/router.go
+++ b/router/router.go
@@ -47,7 +47,7 @@ func GetMainEngine(ctx *context.WchyContext) *echo.Echo {
router.Static("/public", "public")
router.Static("/assets", "node_modules") //TODO: Don't expose node_modules
- router.GET("/oauth/facebook/", handler.OAuth(ctx).Login())
+ router.GET("/oauth/facebook", handler.OAuth(ctx).Login())
router.GET("/oauth/facebook/callback", handler.OAuth(ctx).Callback())
app := router.Group("", MultiTenant(ctx))