Exemplo n.º 1
0
func init() {
	gothic.Store = sessions.NewFilesystemStore(os.TempDir(), []byte("goth-example"))
	goth.UseProviders(
		twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),
		// If you'd like to use authenticate instead of authorize in Twitter provider, use this instead.
		// twitter.NewAuthenticate(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),

		facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), "http://localhost:3000/auth/facebook/callback"),
		gplus.New("281140391713-b1dskle4dtsi6nn4ce01tbkpcp3aovs6.apps.googleusercontent.com", "cIM92vsFvLyfhIZASmAo2ZaE", "http://localhost:8080/auth/gplus/callback"),
		github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback"),
		spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "http://localhost:3000/auth/spotify/callback"),
		linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), "http://localhost:3000/auth/linkedin/callback"),
		lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), "http://localhost:3000/auth/lastfm/callback"),
		twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), "http://localhost:3000/auth/twitch/callback"),
		dropbox.New(os.Getenv("DROPBOX_KEY"), os.Getenv("DROPBOX_SECRET"), "http://localhost:3000/auth/dropbox/callback"),
		digitalocean.New(os.Getenv("DIGITALOCEAN_KEY"), os.Getenv("DIGITALOCEAN_SECRET"), "http://localhost:3000/auth/digitalocean/callback", "read"),
		bitbucket.New(os.Getenv("BITBUCKET_KEY"), os.Getenv("BITBUCKET_SECRET"), "http://localhost:3000/auth/bitbucket/callback"),
		instagram.New(os.Getenv("INSTAGRAM_KEY"), os.Getenv("INSTAGRAM_SECRET"), "http://localhost:3000/auth/instagram/callback"),
		box.New(os.Getenv("BOX_KEY"), os.Getenv("BOX_SECRET"), "http://localhost:3000/auth/box/callback"),
		salesforce.New(os.Getenv("SALESFORCE_KEY"), os.Getenv("SALESFORCE_SECRET"), "http://localhost:3000/auth/salesforce/callback"),
		amazon.New(os.Getenv("AMAZON_KEY"), os.Getenv("AMAZON_SECRET"), "http://localhost:3000/auth/amazon/callback"),
		yammer.New(os.Getenv("YAMMER_KEY"), os.Getenv("YAMMER_SECRET"), "http://localhost:3000/auth/yammer/callback"),
		onedrive.New(os.Getenv("ONEDRIVE_KEY"), os.Getenv("ONEDRIVE_SECRET"), "http://localhost:3000/auth/onedrive/callback"),
	)

	//set a global session
	globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "sessionIDHashFunc": "sha1", "sessionIDHashKey": "", "cookieLifeTime": 3600, "providerConfig": ""}`)
	go globalSessions.GC()
}
Exemplo n.º 2
0
func NewSession(w http.ResponseWriter, r *http.Request, name ...string) *Session {
	var sessionName string

	if len(name) == 0 {
		sessionName = DefaultSessionName
	} else {
		sessionName = name[0]
	}

	s := &Session{
		w: w,
		r: r,
		sessionStore: sessions.NewFilesystemStore(
			"",
			Config.SessionStoreAuthenticationKey,
			Config.SessionStoreEncryptionKey,
		),
	}

	s.sessionStore.Options = &sessions.Options{
		Path:   "/",
		MaxAge: 30 * 60,
	}

	s.session, _ = s.sessionStore.Get(r, sessionName)

	return s
}
Exemplo n.º 3
0
func main() {
	//
	//After user has had opportunity to change config:
	//
	//1 init the db
	db = initdb()
	// Defer the close of the DB in the main function so we'll have a pool of connections maintained until the program exits
	defer db.Close()

	//2 setup our session store
	store = sessions.NewFilesystemStore("", []byte(Config.App.Secret))

	//Initialize the ancillary packages
	forum.Initialize(db)
	user.Initialize(db)
	graf.Initialize(Config, db, store, router, decoder)

	wshub.Initialize(10*time.Second,
		60*time.Second,
		60*time.Second*9/10,
		4096,
		256)

	//Bundled static assets are handled by gotogether
	gotogether.Handle("/static/")

	//Create a subrouter for GET requests
	g := router.Methods("GET").Subrouter()
	g.Handle("/", graf.Handler(graf.AboutHandler)).Name("about")
	g.Handle("/", graf.Handler(graf.IndexHandler)).Name("index")
	g.Handle("/about", graf.Handler(graf.AboutHandler)).Name("about")
	g.Handle("/forum/{id:[0-9]+}", graf.Handler(graf.ForumHandler)).Name("forum")
	g.Handle("/thread/{id:[0-9]+}", graf.Handler(graf.ThreadHandler)).Name("thread")
	g.Handle("/thread", graf.Handler(graf.ThreadRootHandler)).Name("threadRoot") //Form for creating new posts
	g.Handle("/login", graf.Handler(graf.LoginHandler)).Name("login")
	g.Handle("/logout", graf.Handler(graf.LogoutHandler)).Name("logout")
	g.Handle("/register", graf.Handler(graf.RegisterHandler)).Name("register")
	g.HandleFunc(`/ws/thread/{id:[0-9]+}`, graf.ThreadWsHandler)
	g.HandleFunc("/loaderio-38b140f4cb51d3ffca9d71c7529a336d/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "loaderio-38b140f4cb51d3ffca9d71c7529a336d")
	})

	//Create a subrouter for POST requests
	p := router.Methods("POST").Subrouter()
	p.Handle("/thread", graf.Handler(graf.PostThreadHandler)).Name("postThread")
	p.Handle("/login", graf.Handler(graf.PostLoginHandler)).Name("postLogin")
	p.Handle("/register", graf.Handler(graf.PostRegisterHandler)).Name("postRegister")
	p.Handle("/vote", graf.Handler(graf.PostVoteHandler)).Name("postVote")

	//Notify the http package about our router
	http.Handle("/", router)
	fmt.Println("Server launched on port ", Config.App.Port)

	//Launch ws server
	//	go http.ListenAndServe(fmt.Sprintf("%s:8443", Config.App.Host), nil)
	//Launch the server
	if err := http.ListenAndServe(fmt.Sprintf("%s:%s", Config.App.Host, Config.App.Port), nil); err != nil {
		panic(err)
	}
}
Exemplo n.º 4
0
// InitSettings attempts to populate all the fields of the Settings struct. It will return an error if it fails,
// otherwise it returns nil for success.
func (s *Settings) InitSettings(envVars EnvVars) error {
	if len(envVars.ClientID) == 0 {
		return errors.New("Unable to find '" + ClientIDEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.ClientSecret) == 0 {
		return errors.New("Unable to find '" + ClientSecretEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.Hostname) == 0 {
		return errors.New("Unable to find '" + HostnameEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.LoginURL) == 0 {
		return errors.New("Unable to find '" + LoginURLEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.UAAURL) == 0 {
		return errors.New("Unable to find '" + UAAURLEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.APIURL) == 0 {
		return errors.New("Unable to find '" + APIURLEnvVar + "' in environment. Exiting.\n")
	}
	s.ConsoleAPI = envVars.APIURL
	s.LoginURL = envVars.LoginURL
	s.TokenContext = context.TODO()

	// Setup OAuth2 Client Service.
	s.OAuthConfig = &oauth2.Config{
		ClientID:     envVars.ClientID,
		ClientSecret: envVars.ClientSecret,
		RedirectURL:  envVars.Hostname + "/oauth2callback",
		Scopes:       []string{"cloud_controller.read", "cloud_controller.write", "cloud_controller.admin", "scim.read", "openid"},
		Endpoint: oauth2.Endpoint{
			AuthURL:  envVars.LoginURL + "/oauth/authorize",
			TokenURL: envVars.UAAURL + "/oauth/token",
		},
	}

	// Initialize Sessions.
	// Temp FIXME that fixes the problem of using a cookie store which would cause the secure encoding
	// of the oauth 2.0 token struct in production to exceed the max size of 4096 bytes.
	filesystemStore := sessions.NewFilesystemStore("", []byte("some key"))
	filesystemStore.MaxLength(4096 * 4)
	s.Sessions = filesystemStore
	// Want to save a struct into the session. Have to register it.
	gob.Register(oauth2.Token{})

	return nil
}
Exemplo n.º 5
0
func init() {
	util.Configure()
	util.ConfigureLogger()

	var (
		githubKey         = viper.GetString("AUTH_CLIENT_ID")
		githubSecret      = viper.GetString("AUTH_CLIENT_SECRET")
		githubPermissions = []string{"user:email", "repo", "admin:repo_hook", "admin:org_hook", "admin:org"}
		stateTime         = time.Now().UnixNano()
		hash              = strconv.Itoa(int(stateTime))
		err               error
	)

	goth.UseProviders(github.New(githubKey, githubSecret, "", githubPermissions[0], githubPermissions[1], githubPermissions[2], githubPermissions[3], githubPermissions[4]))

	generateFromPassword(err, hash)
	setState()

	gothic.Store = sessions.NewFilesystemStore(os.TempDir(), state_hash)
	getProviderName()
}
Exemplo n.º 6
0
func TestRunAs(t *testing.T) {
	msm := new(DefaultSecurityManager)
	r, _ := realm.NewIni("ini", strings.NewReader(ini))
	msm.SetRealm(r)
	tmpFile, _ := ioutil.TempDir("", "runas")
	msm.SetSessionManager(gorilla.NewGorillaManager(sessions.NewFilesystemStore(tmpFile, []byte("something-very-secret"))))

	subject, _ := msm.CreateSubject(&SubjectContext{
		CreateSessions: true,
		Request:        &http.Request{},
		ResponseWriter: &httptest.ResponseRecorder{},
	})

	subject.Login(authc.NewToken("foo", "password"))

	assert.True(t, subject.IsAuthenticated(), "User is not authenticated after successful login")
	assert.Equal(t, "foo", fmt.Sprintf("%s", subject.Principal()))

	assert.False(t, subject.IsPermitted("everything"))

	err := subject.RunAs([]interface{}{"bar"})

	assert.Nil(t, err)
	assert.True(t, subject.IsAuthenticated(), "User is not authenticated after successful runas")
	assert.Equal(t, "bar", fmt.Sprintf("%s", subject.Principal()))

	assert.True(t, subject.IsPermitted("everything"))

	subject.ReleaseRunAs()

	assert.True(t, subject.IsAuthenticated(), "User is not authenticated after successful runas")
	assert.Equal(t, "foo", fmt.Sprintf("%s", subject.Principal()))

	assert.False(t, subject.IsPermitted("everything"))

}
Exemplo n.º 7
0
// NewFilesystemStore returns a new FilesystemStore.
//
// The path argument is the directory where sessions will be saved. If empty
// it will use os.TempDir().
//
// See NewCookieStore() for a description of the other parameters.
func NewFilesystemStore(path string, keyPairs ...[]byte) FilesystemStore {
	return &filesystemStore{sessions.NewFilesystemStore(path, keyPairs...)}
}
Exemplo n.º 8
0
	cookieName = "pnw_conf"

	authToken = "AUTHID"
	authDate  = "AUTHDA"
	csrfToken = "CSRFTK"

	minPasswordLength = 8

	nsConv    = 1000000000          // second -> nanosecond conversion
	allowance = (3600 * nsConv) * 8 // 8 hours
)

var (
	store = sessions.NewFilesystemStore(
		"store",
		[]byte("2CA434288F3FAB93963CBA1A5B836EEF"),
		[]byte("0655A28CAAEB0448132026D863771C5F"),
	)
)

func init() {
	// Secure cookie options.
	store.Options = &sessions.Options{
		// Domain:   "localhost", // Set this when we have a domain name.
		Path:     "/",
		MaxAge:   3600 * 8, // 8 hours
		HttpOnly: true,
		// Secure:   true, // Set this when TLS is set up.
	}
}
Exemplo n.º 9
0
func CreateSessionStore(secret string, domain string, secure bool) {
	Store = sessions.NewFilesystemStore("", []byte(secret))
	Store.Options = &sessions.Options{Domain: domain, Path: "/", Secure: secure, HttpOnly: true, MaxAge: 7 * 86400}
}
Exemplo n.º 10
0
func init() {
	Store = sessions.NewFilesystemStore(os.TempDir(), []byte(AppKey))
	goth.UseProviders(&faux.Provider{})
}
Exemplo n.º 11
0
func init() {
	gothic.Store = sessions.NewFilesystemStore(os.TempDir(), []byte("goth-example"))
}
Exemplo n.º 12
0
func init() {
	// N.B. this should not be necessary.
	gob.Register(map[PasteID][]byte(nil))
	gob.Register(&PastePermissionSet{})
	gob.Register(PastePermission{})

	arguments.register()
	arguments.parse()

	runtime.GOMAXPROCS(runtime.NumCPU())
	RegisterTemplateFunction("encryptionAllowed", func(ri *RenderContext) bool { return Env() == EnvironmentDevelopment || RequestIsHTTPS(ri.Request) })
	RegisterTemplateFunction("editAllowed", func(ri *RenderContext) bool { return isEditAllowed(ri.Obj.(*Paste), ri.Request) })
	RegisterTemplateFunction("render", renderPaste)
	RegisterTemplateFunction("pasteURL", pasteURL)
	RegisterTemplateFunction("pasteWillExpire", func(p *Paste) bool {
		return p.Expiration != "" && p.Expiration != "-1"
	})
	RegisterTemplateFunction("pasteFromID", func(id PasteID) *Paste {
		p, err := pasteStore.Get(id, nil)
		if err != nil {
			return nil
		}
		return p
	})
	RegisterTemplateFunction("truncatedPasteBody", func(p *Paste, lines int) string {
		reader, _ := p.Reader()
		defer reader.Close()
		bufReader := bufio.NewReader(reader)
		s := ""
		n := 0
		for n < lines {
			line, err := bufReader.ReadString('\n')
			if err != io.EOF && err != nil {
				break
			}
			s = s + line
			if err == io.EOF {
				break
			}
			n++
		}
		if n == lines {
			s += "..."
		}
		return s
	})
	RegisterTemplateFunction("pasteBody", func(p *Paste) string {
		reader, _ := p.Reader()
		defer reader.Close()
		b := &bytes.Buffer{}
		io.Copy(b, reader)
		return b.String()
	})
	RegisterTemplateFunction("requestVariable", requestVariable)

	sesdir := filepath.Join(arguments.root, "sessions")
	os.Mkdir(sesdir, 0700)

	sessionKeyFile := filepath.Join(arguments.root, "session.key")
	sessionKey, err := SlurpFile(sessionKeyFile)
	if err != nil {
		sessionKey = securecookie.GenerateRandomKey(32)
		err = ioutil.WriteFile(sessionKeyFile, sessionKey, 0600)
		if err != nil {
			glog.Fatal("session.key not found, and an attempt to create one failed: ", err)
		}
	}
	sessionStore = sessions.NewFilesystemStore(sesdir, sessionKey)
	sessionStore.Options.Path = "/"
	sessionStore.Options.MaxAge = 86400 * 365

	clientKeyFile := filepath.Join(arguments.root, "client_session_enc.key")
	clientOnlySessionEncryptionKey, err := SlurpFile(clientKeyFile)
	if err != nil {
		clientOnlySessionEncryptionKey = securecookie.GenerateRandomKey(32)
		err = ioutil.WriteFile(clientKeyFile, clientOnlySessionEncryptionKey, 0600)
		if err != nil {
			glog.Fatal("client_session_enc.key not found, and an attempt to create one failed: ", err)
		}
	}
	clientOnlySessionStore = sessions.NewCookieStore(sessionKey, clientOnlySessionEncryptionKey)
	if Env() != EnvironmentDevelopment {
		clientOnlySessionStore.Options.Secure = true
	}
	clientOnlySessionStore.Options.Path = "/"
	clientOnlySessionStore.Options.MaxAge = 0

	clientLongtermSessionStore = sessions.NewCookieStore(sessionKey, clientOnlySessionEncryptionKey)
	if Env() != EnvironmentDevelopment {
		clientLongtermSessionStore.Options.Secure = true
	}
	clientLongtermSessionStore.Options.Path = "/"
	clientLongtermSessionStore.Options.MaxAge = 86400 * 365

	pastedir := filepath.Join(arguments.root, "pastes")
	os.Mkdir(pastedir, 0700)
	pasteStore = NewFilesystemPasteStore(pastedir)
	pasteStore.PasteDestroyCallback = PasteCallback(pasteDestroyCallback)

	pasteExpirator = gotimeout.NewExpirator(filepath.Join(arguments.root, "expiry.gob"), &ExpiringPasteStore{pasteStore})
	ephStore = gotimeout.NewMap()

	accountPath := filepath.Join(arguments.root, "accounts")
	os.Mkdir(accountPath, 0700)
	userStore = &PromoteFirstUserToAdminStore{
		Path: accountPath,
		AccountStore: &CachingUserStore{
			AccountStore: &ManglingUserStore{
				account.NewFilesystemStore(accountPath, &AuthChallengeProvider{}),
			},
		},
	}
}
Exemplo n.º 13
0
// InitSettings attempts to populate all the fields of the Settings struct. It will return an error if it fails,
// otherwise it returns nil for success.
func (s *Settings) InitSettings(envVars EnvVars) error {
	if len(envVars.ClientID) == 0 {
		return errors.New("Unable to find '" + ClientIDEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.ClientSecret) == 0 {
		return errors.New("Unable to find '" + ClientSecretEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.Hostname) == 0 {
		return errors.New("Unable to find '" + HostnameEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.LoginURL) == 0 {
		return errors.New("Unable to find '" + LoginURLEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.UAAURL) == 0 {
		return errors.New("Unable to find '" + UAAURLEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.APIURL) == 0 {
		return errors.New("Unable to find '" + APIURLEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.LogURL) == 0 {
		return errors.New("Unable to find '" + LogURLEnvVar + "' in environment. Exiting.\n")
	}
	if len(envVars.SessionKey) == 0 {
		return errors.New("Unable to find '" + SessionKeyEnvVar + "' in environment. Exiting.\n")
	}

	s.ConsoleAPI = envVars.APIURL
	s.LoginURL = envVars.LoginURL
	s.TokenContext = context.TODO()
	s.UaaURL = envVars.UAAURL
	s.LogURL = envVars.LogURL
	s.PProfEnabled = ((envVars.PProfEnabled == "true") || (envVars.PProfEnabled == "1"))
	if s.BuildInfo = envVars.BuildInfo; len(s.BuildInfo) == 0 {
		s.BuildInfo = "developer-build"
	}
	s.SecureCookies = ((envVars.SecureCookies == "true") || (envVars.SecureCookies == "1"))

	// Setup OAuth2 Client Service.
	s.OAuthConfig = &oauth2.Config{
		ClientID:     envVars.ClientID,
		ClientSecret: envVars.ClientSecret,
		RedirectURL:  envVars.Hostname + "/oauth2callback",
		Scopes:       []string{"cloud_controller.read", "cloud_controller.write", "cloud_controller.admin", "scim.read", "openid"},
		Endpoint: oauth2.Endpoint{
			AuthURL:  envVars.LoginURL + "/oauth/authorize",
			TokenURL: envVars.UAAURL + "/oauth/token",
		},
	}

	s.StateGenerator = func() (string, error) {
		return GenerateRandomString(32)
	}

	// Initialize Sessions.
	// Temp FIXME that fixes the problem of using a cookie store which would cause the secure encoding
	// of the oauth 2.0 token struct in production to exceed the max size of 4096 bytes.
	filesystemStore := sessions.NewFilesystemStore("", []byte(envVars.SessionKey))
	filesystemStore.MaxLength(4096 * 4)
	filesystemStore.Options = &sessions.Options{
		HttpOnly: true,
		Secure:   s.SecureCookies,
	}
	s.Sessions = filesystemStore
	// Want to save a struct into the session. Have to register it.
	gob.Register(oauth2.Token{})

	s.HighPrivilegedOauthConfig = &clientcredentials.Config{
		ClientID:     envVars.ClientID,
		ClientSecret: envVars.ClientSecret,
		Scopes:       []string{"scim.read"},
		TokenURL:     envVars.UAAURL + "/oauth/token",
	}

	return nil
}
Exemplo n.º 14
0
package lib

import (
	"github.com/go4r/handy"
	"github.com/gorilla/sessions"
	"net/http"
	"net/url"
)

var (
	DefaultSessionKeyPars                = [][]byte{[]byte(`2TZs4ESupxTybxm9JYXEeV6FuvI8YNKA`)}
	DefaultSessionStore   sessions.Store = sessions.NewFilesystemStore("private/sessions", DefaultSessionKeyPars...)
	DefaultSessionName                   = "handy_session"
)

func init() {
	handy.Server.Context().MapProviders(handy.ProvidersMap{
		"cookies": func(c *handy.Context) func() interface{} {
			var cookies = &Cookies{map[string]*http.Cookie{}, c.Get("request").(*http.Request)}
			c.CleanupFunc(func() {
				w := c.Get("response").(http.ResponseWriter)
				for _, v := range cookies.Cookies {
					v.Value = url.QueryEscape(v.Value)
					http.SetCookie(w, v)
				}
			})
			return func() interface{} {
				return cookies
			}
		},
		"session.store": func(c *handy.Context) func() interface{} {
Exemplo n.º 15
0
package main

import (
	"github.com/gorilla/securecookie"
	"github.com/gorilla/sessions"
	"time"
)

// Session store for users
var store = sessions.NewFilesystemStore(
	// Path
	"app/sessions",
	// Secret key with strength set to 64
	[]byte(securecookie.GenerateRandomKey(64)),
)

type User struct {
	// ID is an int64 that is a users identification
	// number.
	Id uint64

	// Username is a string with max-size set to 255
	// and is the username that a user will use when
	// logging in to the web interface.
	Username string `sql:"size:255;unique"`

	// Password is a string with max-size set to 255
	// and is the password that a user will use when
	// logging in to the web interface.
	Password string `sql:"size:255"`