Ejemplo n.º 1
0
func init() {
	peopleModel = model.PeopleModel{"people"}
	store = sessions.NewCookieStore([]byte("hellogolang.org"))
	postModel = model.PostModel{"post"}
	postClassModel = model.PostClassModel{"post_class"}
	commentModel = model.CommentModel{"comment"}
}
Ejemplo n.º 2
0
func main() {
	var err error
	session, err = mgo.Dial(os.Getenv("DATABASE_URL"))
	if err != nil {
		panic(err)
	}
	database = session.DB("").Name

	//create an index for the username field on the users collection
	if err := session.DB("").C("users").EnsureIndex(mgo.Index{
		Key:    []string{"username"},
		Unique: true,
	}); err != nil {
		panic(err)
	}

	store = sessions.NewCookieStore([]byte(os.Getenv("KEY")))

	router = pat.New()
	router.Add("GET", "/login", handler(loginForm)).Name("login")
	router.Add("POST", "/login", handler(login))

	router.Add("GET", "/register", handler(registerForm)).Name("register")
	router.Add("POST", "/register", handler(register))

	router.Add("GET", "/logout", handler(logout)).Name("logout")

	router.Add("GET", "/", handler(hello)).Name("index")

	router.Add("POST", "/sign", handler(sign)).Name("sign")

	if err = http.ListenAndServe(":"+os.Getenv("PORT"), router); err != nil {
		panic(err)
	}
}
Ejemplo n.º 3
0
func main() {
	var cfgfile *string = flag.String("config", "", "configuration file")
	flag.Parse()

	if *cfgfile == "" {
		flag.Usage()
		os.Exit(1)
	}

	log.Printf("this is activities, revision %s", gitRevision)
	log.Printf("GOMAXPROCS = %d", runtime.GOMAXPROCS(0))
	log.Printf("NumCPU = %d", runtime.NumCPU())

	cfg, err := goconf.ReadConfigFile(*cfgfile)

	// TODO: add error handling
	driver, _ := cfg.GetString("database", "driver")
	dsn, _ := cfg.GetString("database", "dsn")
	auth_key, _ := cfg.GetString("sessions", "authkey")
	enc_key, _ := cfg.GetString("sessions", "enckey")

	db_handle, err := sql.Open(driver, dsn)
	if err != nil {
		log.Fatalf("sql.Open: %v", err)
	}
	defer db_handle.Close()

	db := NewDatabase(db_handle)

	store := sessions.NewCookieStore([]byte(auth_key), []byte(enc_key))

	r := pat.New()

	r.Add("POST", "/auth/try", &TryAuthenticateHandler{Db: db, Store: store})
	r.Add("POST", "/auth/signup", &SignupHandler{Db: db})
	r.Add("POST", "/auth/logout", &LogoutHandler{Store: store})
	r.Add("POST", "/auth", &AuthenticateHandler{Db: db, Store: store})
	r.Add("POST", "/activity/add", &AddActivityHandler{Store: store, Db: db})
	r.Add("GET", "/activity/list/{page:[0-9]+}", &ListActivitiesHandler{Db: db, Store: store})
	r.Add("POST", "/activity/type/add", &AddActivityTypeHandler{Db: db, Store: store})
	r.Add("POST", "/activity/type/edit", &EditActivityTypeHandler{Db: db, Store: store})
	r.Add("POST", "/activity/type/del", &DeleteActivityTypeHandler{Db: db, Store: store})
	r.Add("GET", "/activity/type/list", &ListActivityTypesHandler{Db: db, Store: store})
	r.Add("GET", "/activity/latest", &LatestActivitiesHandler{Db: db, Store: store})
	r.Add("GET", "/", http.FileServer(http.Dir("htdocs")))

	httpsrv := &http.Server{Handler: Logger(r), Addr: ":8000"}
	if err := httpsrv.ListenAndServe(); err != nil {
		log.Fatalf("ListenAndServe: %v", err)
	}
}
Ejemplo n.º 4
0
func main() {
	var cfgfile *string = flag.String("config", "", "configuration file")
	flag.Parse()

	if *cfgfile == "" {
		flag.Usage()
		os.Exit(1)
	}

	cfg, err := goconf.ReadConfigFile(*cfgfile)

	// TODO: add error handling
	driver, _ := cfg.GetString("database", "driver")
	dsn, _ := cfg.GetString("database", "dsn")
	auth_key, _ := cfg.GetString("sessions", "authkey")
	enc_key, _ := cfg.GetString("sessions", "enckey")

	db, err = sql.Open(driver, dsn)
	if err != nil {
		log.Fatalf("sql.Open: %v", err)
	}
	defer db.Close()

	store = sessions.NewCookieStore([]byte(auth_key), []byte(enc_key))

	r := pat.New()

	r.Post("/auth/try", http.HandlerFunc(TryAuthenticate))
	r.Post("/auth/signup", http.HandlerFunc(Signup))
	r.Post("/auth/logout", http.HandlerFunc(Logout))
	r.Post("/auth", http.HandlerFunc(Authenticate))
	r.Post("/activity/add", http.HandlerFunc(AddActivity))
	r.Get("/activity/list/{page:[0-9]+}", http.HandlerFunc(ListActivities))
	r.Post("/activity/type/add", http.HandlerFunc(AddActivityType))
	r.Post("/activity/type/edit", http.HandlerFunc(EditActivityType))
	r.Post("/activity/type/del", http.HandlerFunc(DeleteActivityType))
	r.Get("/activity/type/list", http.HandlerFunc(ListActivityTypes))

	r.Get("/activity/latest", http.HandlerFunc(LatestActivities))
	r.Add("GET", "/", http.FileServer(http.Dir("htdocs")))

	httpsrv := &http.Server{Handler: r, Addr: ":8000"}
	if err := httpsrv.ListenAndServe(); err != nil {
		log.Fatalf("ListenAndServe: %v", err)
	}
}
Ejemplo n.º 5
0
func TestAuthenticateHandler(t *testing.T) {
	testdata := []struct {
		auth_data            string
		http_code            int
		authenticated_result bool
	}{
		{"username=foo&password=bar", http.StatusOK, true},
		{"username=invalid&password=invalid", http.StatusOK, false},
	}

	for _, td := range testdata {
		req, _ := http.NewRequest("POST", "http://localhost/auth", bytes.NewBufferString(td.auth_data))
		req.Header["Content-Length"] = []string{fmt.Sprintf("%d", len(td.auth_data))}
		req.Header["Content-Type"] = []string{"application/x-www-form-urlencoded"}

		mock_db := &MockCredentialsVerifierActivityTypesGetter{}

		handler := &AuthenticateHandler{Db: mock_db, Store: sessions.NewCookieStore([]byte(""))}

		resp := NewMockResponseWriter()

		handler.ServeHTTP(resp, req)

		if resp.StatusCode != td.http_code {
			t.Errorf("AuthenticateHandler responded with %d (expected: %d)", resp.StatusCode, td.http_code)
		}

		if len(resp.Header()["Content-Type"]) < 1 || resp.Header()["Content-Type"][0] != "application/json" {
			t.Errorf("AuthenticateHandler sends wrong Content-Type (%v)", resp.Header()["Content-Type"][0])
		}

		data := make(map[string]interface{})
		if err := json.Unmarshal(resp.Buffer.Bytes(), &data); err != nil {
			t.Errorf("AuthenticateHandler returned invalid JSON: %v", err)
		}

		if authenticated, ok := data["authenticated"].(bool); !ok {
			t.Errorf("JSON authenticated field didn't contain bool")
		} else {
			if authenticated != td.authenticated_result {
				t.Errorf("AuthenticateHandler authenticated returns %v (expected %v)", authenticated, td.authenticated_result)
			}
		}
	}
}
Ejemplo n.º 6
0
func init() {
	logFile, err := os.OpenFile("systic.log", os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Printf("Couldn't open systic.log. Logging to stdout.\n")
	} else {
		log.SetOutput(logFile)
	}

	Config, err := config.LoadConfig(filepath.Join("config", "app.conf"))
	if err != nil {
		log.Fatalf("Couldn't read app.conf: %s\n", err)
	}

	appName = Config.AppName

	if len(Config.Secret) < 20 {
		log.Fatalln("That secret in app.conf is not long enough! Make it hella long!")
	}
	Jar = sessions.NewCookieStore([]byte(Config.Secret))
}
Ejemplo n.º 7
0
func main() {
	store = sessions.NewCookieStore([]byte("rape"))

	var c = ballsite.BallCount()
	fmt.Println("Ball count:", c)

	/*
		var ball = ballsite.Ball{}
		ball.Title = "First Ball"
		ball.Description = "Dies ist der erste Ball mit dem storm clouds and rainbow image"
		ball.ImagePath = "/var/www/polandball/media/images/storm_clouds_and_rainbow-wallpaper-1920x1200.jpg"
		ball.ThumbPath = "/var/www/polandball/media/thumbnails/storm_clouds_and_rainbow-wallpaper-1920x1200.jpg.png"

		fmt.Println("before insert:", ball)
		ball = ballsite.InsertBall(ball)
		fmt.Println("after insert:", ball)


		ball = ballsite.Ball{}
		ball.Title = "Second Ball"
		ball.Description = "Dies ist der zweite Ball mit dem hacker redux image"
		ball.ImagePath = "/var/www/polandball/media/images/hacker_redux_by_hashbox.png"
		ball.ThumbPath = "/var/www/polandball/media/thumbnails/hacker_redux_by_hashbox.png.png"

		fmt.Println("before insert:", ball)
		ball = ballsite.InsertBall(ball)
		fmt.Println("after insert:", ball)

		return
	*/

	http.Handle("/", makeHandler(index))
	http.Handle("/ball/", makeHandler(ball))
	http.Handle("/rand", makeHandler(random))
	http.Handle("/view/image/", makeHandler(image))
	http.Handle("/view/thumbnail/", makeHandler(thumb))
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 8
0
func init() {
	logFile, err := os.OpenFile("systic.log", os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Printf("Couldn't open systic.log. Logging to stdout.\n")
	} else {
		log.SetOutput(logFile)
	}

	configBytes, err := ioutil.ReadFile(srcPath)
	if err != nil {
		log.Fatalf("Couldn't read app.conf: %s\n", err)
	}

	err = json.Unmarshal(configBytes, &config)
	if err != nil {
		log.Fatalf("Error unmarshalling app.conf: %s\n", err)
	}

	appName = config["appname"].(string)

	Jar = sessions.NewCookieStore([]byte(config["secret"]))
}
Ejemplo n.º 9
0
	"any": Any,
}

func randInt(min int, max int) int {
	return min + rand.Intn(max-min)
}

func randomString(l int) string {
	bytes := make([]byte, l)
	for i := 0; i < l; i++ {
		bytes[i] = byte(randInt(65, 90))
	}
	return string(bytes)
}

var Store = sessions.NewCookieStore([]byte(randomString(100)))

// any reports whether the first argument is equal to
// any of the remaining arguments.
func Any(args ...interface{}) bool {
	if len(args) == 0 {
		return false
	}
	x := args[0]
	switch x := x.(type) {
	case string, int, int64, byte, float32, float64:
		for _, y := range args[1:] {
			if x == y {
				return true
			}
		}
Ejemplo n.º 10
0
func init() {

	if config["db"] == "" {
		println("数据库地址还没有配置,请到config.json内配置db字段.")
		return
	}

	session, err := mgo.Dial(config["db"])
	if err != nil {
		panic(err)
	}

	session.SetMode(mgo.Monotonic, true)

	db = session.DB("gopher")

	cookie_secret := config["cookie_secret"]

	store = sessions.NewCookieStore([]byte(cookie_secret))

	utils = &Utils{}

	// 如果没有status,创建
	var status Status
	c := db.C("status")
	err = c.Find(nil).One(&status)

	if err != nil {
		c.Insert(&Status{
			Id_:        bson.NewObjectId(),
			UserCount:  0,
			TopicCount: 0,
			ReplyCount: 0,
			UserIndex:  0,
		})
	}

	// 检查是否有超级账户设置
	var superusers []string
	for _, username := range strings.Split(config["superusers"], ",") {
		username = strings.TrimSpace(username)
		if username != "" {
			superusers = append(superusers, username)
		}
	}

	if len(superusers) == 0 {
		println("你没有设置超级账户,请在config.json中的superusers中设置,如有多个账户,用逗号分开")
	}

	c = db.C("users")
	var users []User
	c.Find(bson.M{"issuperuser": true}).All(&users)

	// 如果mongodb中的超级用户不在配置文件中,取消超级用户
	for _, user := range users {
		if !stringInArray(superusers, user.Username) {
			c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"issuperuser": false}})
		}
	}

	// 设置超级用户
	for _, username := range superusers {
		c.Update(bson.M{"username": username, "issuperuser": false}, bson.M{"$set": bson.M{"issuperuser": true}})
	}
}
Ejemplo n.º 11
0
package sessions

import (
	"code.google.com/p/gorilla/sessions"
	"net/http"
)

const (
	_ = iota
	Anonymous
	User
)

var (
	store = sessions.NewCookieStore([]byte("NiseGoPostSecret"))
)

type Session struct {
	*sessions.Session
}

func Get(r *http.Request) *Session {
	s, _ := store.Get(r, "session")
	return &Session{s}
}

func New(r *http.Request) *Session {
	s, _ := store.New(r, "session")
	s.Values["hasError"] = false
	return &Session{s}
}
Ejemplo n.º 12
0
Archivo: app.go Proyecto: jbaikge/goci
	recent_amount = 20
)

var (
	mode = tmplmgr.Production

	//TODO: make sure these things happen after the env import
	assets_dir       = filepath.Join(env("APPROOT", ""), "assets")
	template_dir     = filepath.Join(env("APPROOT", ""), "templates")
	dist_dir         = filepath.Join(env("APPROOT", ""), "dist")
	base_template    = tmplmgr.Parse(tmpl_root("base.tmpl"))
	recent_template  = tmplmgr.Parse(tmpl_root("recent.tmpl"))
	current_template = tmplmgr.Parse(tmpl_root("current.tmpl"))

	store     = sessions.NewCookieStore([]byte(store_key))
	base_meta = &Meta{
		CSS: list{
			"bootstrap-superhero.min.css",
			// "bootstrap-responsive.min.css",
			"main.css",
		},
		JS: list{
			"jquery.min.js",
			"jquery-ui.min.js",
			"bootstrap.js",
			"status.js",
			"main.js",
		},
		BaseTitle: "GoCI",
	}
Ejemplo n.º 13
0
import (
	"code.google.com/p/gorilla/sessions"
	"errors"
	"fmt"
	"github.com/fzzbt/radix"
	"net/http"
	"net/url"
	"time"
)

var ErrUserNotLoggedIn = errors.New("session: user not logged in")
var ErrResourceRedirected = errors.New("session: resource was redirected")

// used for flashes
var sessionStore = sessions.NewCookieStore([]byte("something-very-secret"))

type session struct {
	id   string
	user *user
}

// Fetch user from cookie, set cookie, sync cookies x-domain
// main cookie flexer, called before every resource handler
func userCookie(w http.ResponseWriter, r *http.Request) (u *user, err error) {

	// login cookie
	c, err := r.Cookie("vafanLogin")
	if err != nil {
		if err == http.ErrNoCookie {
			err = nil
Ejemplo n.º 14
0
/*
	sessioner stores your session variables
*/
package sessioner

import (
	"code.google.com/p/gorilla/sessions"
	"net/http"
)

var store = sessions.NewCookieStore([]byte("Go Game Lobby!"))

/*
	The Session is the interface exposed to the rest of the program
*/
type Session interface {
	Set(k, v interface{})            // Set will set a session variable
	Get(k interface{}) interface{}   //Get will obtain the result of a session variable
	Clear(k interface{}) interface{} //Clear will obstain the result of a session variable, and then delete it from the session value
}

type session struct {
	sess *sessions.Session
	r    *http.Request
}

func (this *session) Set(k, v interface{}) {
	this.sess.Values[k] = v
}

func (this *session) Get(k interface{}) interface{} {
Ejemplo n.º 15
0
	"code.google.com/p/gorilla/schema"
	"code.google.com/p/gorilla/sessions"
	"fmt"
	"html/template"
	"log"
	"net/http"
)

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/order", OrderHandler)
	r.HandleFunc("/order/{id}", ViewHandler)
	log.Fatal(http.ListenAndServe(":8080", r))
}

var store = sessions.NewCookieStore([]byte("randomsecrets"))

func Reply(file string, w http.ResponseWriter, r *http.Request, session *sessions.Session) {
	buf := bufio.NewWriter(w)
	t, _ := template.ParseFiles(file)
	t.Execute(buf, session)
	session.Save(r, w)
	buf.Flush()
}

var itemlist = []string{"Bacon", "Ham", "More bacon"}

func ViewHandler(w http.ResponseWriter, r *http.Request) {
	PreventCaching(w)

	session, _ := store.Get(r, "session-stuff")
Ejemplo n.º 16
0
package main

import (
	"code.google.com/p/gorilla/sessions"
	"html/template"
	"log"
	"net/http"
	"os"
)

const cookieSecret = "" // put a random string here
const sessionName = ""  // sensible name related to your app

// cookie store for sessions
var store = sessions.NewCookieStore([]byte(cookieSecret))

const defaultPort = "12000" // change it

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = defaultPort
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tmpl := template.New("main.html")
		tmpl, err := tmpl.ParseGlob("templates/*.html")
		if err != nil {
			log.Println("error parsing:", err)
		}
Ejemplo n.º 17
0
	}

	address := controller.processRequest(w, r)
	if strings.HasPrefix(address, "redirect:") {
		address = "/" + strings.SplitAfterN(address, ":", 2)[1]
		http.Redirect(w, r, address, http.StatusFound)
		return

	}

	// html/template oletuksena estää injektiot
	t := getTemplate(address)
	t.Execute(w, r)
}

var store = sessions.NewCookieStore([]byte("baconbaconbacon"))

//----------

type Controller interface {
	processRequest(w http.ResponseWriter, r *http.Request) string
}

type IndexController struct{}

func (c *IndexController) processRequest(w http.ResponseWriter, r *http.Request) string {
	return "login.html"
}

type LoginController struct {
}
Ejemplo n.º 18
0
package hello

import (
	"fmt"
	"net/http"

	"code.google.com/p/gorilla/mux"
	"code.google.com/p/gorilla/sessions"

	gaeSessions "code.google.com/p/gorilla/appengine/sessions"
)

var router = new(mux.Router)
var store = sessions.NewCookieStore([]byte("my-secret-key"),
	[]byte("1234567890123456"))
var dStore = gaeSessions.NewDatastoreStore("", []byte("my-secret-key"),
	[]byte("1234567890123456"))
var mStore = gaeSessions.NewMemcacheStore("", []byte("my-secret-key"),
	[]byte("1234567890123456"))

func init() {
	// Register a couple of routes.
	router.HandleFunc("/", homeHandler).Name("home")
	router.HandleFunc("/{salutation}/{name}", helloHandler).Name("hello")
	router.HandleFunc("/datastore-session", datastoreSessionHandler).Name("datastore-session")
	router.HandleFunc("/cookie-session", cookieSessionHandler).Name("cookie-session")
	router.HandleFunc("/memcache-session", memcacheSessionHandler).Name("memcache-session")
	// Send all incoming requests to router.
	http.Handle("/", router)
}
Ejemplo n.º 19
0
Archivo: store.go Proyecto: scotch/aego
// Copyright 2012 The AEGo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Package session provides an interface for Sessions. Currently using:

	"code.google.com/p/gorilla/sessions"

*/
package session

import (
	"code.google.com/p/gorilla/sessions"
	//"config"
)

// Store is a gorilla/session store.
var Store = sessions.NewCookieStore([]byte("123456789"))

//var Store = sessions.NewCookieStore([]byte(config.SecretKey))
Ejemplo n.º 20
0
// 由于golang 可以直接仍个编译后的文件过去
// 所以密码采用 email+raw_pwd 进行加密,即使数据库被盗,源码对方也看不到,无法了解加密方式,破解难度提高 加密方式是 bcrypt
package user

import (
	"labix.org/v2/mgo"
	"os"
	//"fmt"
	"code.google.com/p/gorilla/sessions"
	"encoding/json"
	//"io/ioutil"
	//"text/template"
)

var store = sessions.NewCookieStore([]byte("secret-code"))

/*
   config/user.json 是用户模块的专属配置文件
   里面有:
       "db": "localhost",
       "email": "*****@*****.**",
       "pwd": "xxx"

*/
var config map[string]string

//var email_tmpl *template.Template
var db_user, db_resertpwd *mgo.Collection

func readConfig() {
	// 读取配置文件
Ejemplo n.º 21
0
func runHttpServer(cfg *musebot.JsonCfg) {
	if len(cfg.SessionStoreAuthKey) != 32 && len(cfg.SessionStoreAuthKey) != 64 {
		b64 := base64.StdEncoding
		log.Fatalln("SessionStoreAuthKey must be 32 or 64 bytes long, not", len(cfg.SessionStoreAuthKey), "bytes! Here's a suggested value:", b64.EncodeToString(securecookie.GenerateRandomKey(64)))
	}
	sessionStore = sessions.NewCookieStore(cfg.SessionStoreAuthKey)

	// let's try to get the default provider
	defaultProvider, wasFound := musebot.CurrentProviders[config.DefaultProvider]
	if !wasFound {
		for _, p := range musebot.CurrentProviders {
			defaultProvider = p
			break
		}
	}

	// job ID generator
	go func(generatorPipe chan int) {
		i := 0
		for {
			generatorPipe <- i
			i = i + 1
		}
	}(jobIdGenerator)

	var eProviderNotFound = errors.New("Provider not found")

	// GO GO WEB HANDLER
	http.HandleFunc("/api/current_song/", func(w http.ResponseWriter, r *http.Request) {
		if !enforceLoggedIn(getSession(r), w) {
			return
		}

		currentSong, isPlaying, err := musebot.CurrentBackend.CurrentSong()
		if err != nil {
			writeApiResponse(w, wrapApiError(err))
		} else {
			if isPlaying {
				writeApiResponse(w, musebot.CurrentSongApiResponse{Playing: isPlaying, CurrentSong: &currentSong})
			} else {
				writeApiResponse(w, musebot.CurrentSongApiResponse{Playing: isPlaying, CurrentSong: nil})
			}
		}
	})

	http.HandleFunc("/api/playback_queue/", func(w http.ResponseWriter, r *http.Request) {
		if !enforceLoggedIn(getSession(r), w) {
			return
		}

		playbackQueue, err := musebot.CurrentBackend.PlaybackQueue()
		if err != nil {
			writeApiResponse(w, wrapApiError(err))
		} else {
			writeApiResponse(w, musebot.PlaybackQueueApiResponse{playbackQueue})
		}
	})

	http.HandleFunc("/api/search_and_queue_first/", func(w http.ResponseWriter, r *http.Request) {
		if !enforceLoggedIn(getSession(r), w) {
			return
		}

		// get the query!
		queryStrMap := r.URL.Query()
		queryArray, ok := queryStrMap["q"]
		if !ok || len(queryArray) < 1 || len(queryArray[0]) == 0 {
			writeApiResponse(w, wrapApiError(errors.New("You must pass a 'q' argument specifying the query!")))
			return
		}

		query := queryArray[0]
		// cool

		searchRes, err := musebot.CurrentProviders["provider.GroovesharkProvider"].Search(query)
		if err != nil {
			writeApiResponse(w, wrapApiError(err))
			return
		}

		if len(searchRes) == 0 {
			writeApiResponse(w, wrapApiError(errors.New("There were no results for that query.")))
			return
		}

		fetchChan := make(chan musebot.ProviderMessage, 1000)
		log.Println(searchRes[0].Title)

		go searchRes[0].Provider.FetchSong(&searchRes[0], fetchChan)

		waitToEnd := make(chan bool)

		go (func(fetchChan chan musebot.ProviderMessage, song *musebot.SongInfo, done chan bool) {
			for {
				msg := <-fetchChan
				log.Println(msg)
				if msg.Type == "done" {
					musebot.CurrentBackend.Add(*song)
					writeApiResponse(w, musebot.QueuedApiResponse{*song})
					done <- true
					return
				} else if msg.Type == "error" {
					writeApiResponse(w, wrapApiError(msg.Content.(error)))
					done <- true
					return
				}
			}
		})(fetchChan, &searchRes[0], waitToEnd)

		<-waitToEnd

	})

	http.HandleFunc("/api/available_providers/", func(w http.ResponseWriter, r *http.Request) {
		if !enforceLoggedIn(getSession(r), w) {
			return
		}

		outputBlah := make(map[string]string)
		for k, v := range musebot.CurrentProviders {
			outputBlah[k] = v.Name()
		}
		writeApiResponse(w, musebot.AvailableProvidersApiResponse{outputBlah})
	})

	http.HandleFunc("/api/search/", func(w http.ResponseWriter, r *http.Request) {
		if !enforceLoggedIn(getSession(r), w) {
			return
		}

		// get the query!
		queryStrMap := r.URL.Query()
		qArray, ok := queryStrMap["q"]
		if !ok || len(qArray) < 1 || len(qArray[0]) == 0 {
			writeApiResponse(w, wrapApiError(errors.New("You must pass a 'q' argument specifying the query!")))
			return
		}

		q := qArray[0]

		// now the provider
		providerArray, ok := queryStrMap["provider"]
		var provider provider.Provider
		if !ok || len(providerArray) < 1 || len(providerArray[0]) == 0 {
			provider = defaultProvider
		} else {
			providerName := providerArray[0]
			provider, ok = musebot.CurrentProviders[providerName]
			if !ok {
				writeApiResponse(w, wrapApiError(eProviderNotFound))
				return
			}
		}

		// now we have a provider, we can search!
		searchResults, err := provider.Search(q)
		if err != nil {
			writeApiResponse(w, wrapApiError(err))
			return
		}
		writeApiResponse(w, musebot.SearchResultsApiResponse{searchResults})
	})

	http.HandleFunc("/api/logout/", func(w http.ResponseWriter, r *http.Request) {
		sess := getSession(r)
		result := true
		if !isLoggedIn(sess) {
			result = false
		}

		// cool
		sess.Values = map[interface{}]interface{}{}
		sess.Save(r, w)

		writeApiResponse(w, musebot.LoggedOutApiResponse{result})
		return
	})

	http.HandleFunc("/api/quit/", func(w http.ResponseWriter, r *http.Request) {
		if !enforceLoggedIn(getSession(r), w) {
			return
		}

		log.Println()
		log.Println("Exiting on request!")
		os.Exit(0)
	})

	http.HandleFunc("/api/add_to_queue/", func(w http.ResponseWriter, r *http.Request) {
		sess := getSession(r)
		if !enforceLoggedIn(sess, w) {
			return
		}

		providerName := r.FormValue("provider")
		providerId := r.FormValue("provider_id")

		si := musebot.SongInfo{}
		si.ProviderName = providerName
		si.ProviderId = providerId
		provider, exists := musebot.CurrentProviders[providerName]

		if !exists {
			writeApiResponse(w, wrapApiError(errors.New("That provider doesn't exist.")))
		}

		si.Provider = provider

		log.Println("UPDATING SONG INFO")

		si.Provider.UpdateSongInfo(&si)

		log.Println(si)

		provMessage := make(chan musebot.ProviderMessage)
		quit := make(chan bool)
		go si.Provider.FetchSong(&si, provMessage)

		log.Println(si, provMessage)

		log.Println(sess.Values["username"])

		go func(quit chan bool, provMessage chan musebot.ProviderMessage, w http.ResponseWriter, s *musebot.SongInfo, user string) {
			hasQuit := false
			jobId := <-jobIdGenerator
			var m musebot.ProviderMessage
			for {
				m = <-provMessage
				if m.Type == "error" {
					if !hasQuit {
						writeApiResponse(w, wrapApiError(m.Content.(error)))
						quit <- true
						return // done
					}
				} else if m.Type == "stages" {
					if !hasQuit {
						// tell them that we're AWESOME
						if m.Content == 0 {
							log.Println("ORDERING BACKEND TO ADD", s)
							musebot.CurrentBackend.Add(*s)
							writeApiResponse(w, musebot.QueuedApiResponse{*s})
							quit <- true
							return // done
						} else {
							writeApiResponse(w, musebot.JobQueuedApiResponse{strconv.Itoa(jobId)})
							quit <- true
							hasQuit = true
						}
					}
				} else if m.Type == "done" && hasQuit {
					musebot.CurrentBackend.Add(*s)
				}
				if hasQuit {
					outputData := musebot.JobWebSocketApiResponse{JobId: strconv.Itoa(jobId), Data: m}
					jsonData, _ := json.Marshal(outputData)
					userOutputData := UserMessage{user: user, message: "JOB_DATA " + string(jsonData)}
					h.broadcastUser <- userOutputData
				}
			}
		}(quit, provMessage, w, &si, sess.Values["username"].(string))

		<-quit

	})

	http.HandleFunc("/api/login/", func(w http.ResponseWriter, r *http.Request) {
		if r.TLS == nil {
			writeApiResponse(w, wrapApiError(errors.New("This method requires TLS! :<")))
			return
		}

		sess := getSession(r)

		username := r.FormValue("username")
		password := r.FormValue("password")

		a := musebot.CurrentAuthenticator
		result, user, err := a.CheckLogin(username, password)
		if err != nil {
			writeApiResponse(w, wrapApiError(err))
			return
		}
		if result {
			sess.Values["logged-in"] = true
			sess.Values["username"] = user.Username
			sess.Values["administrator"] = user.Administrator
			sess.Save(r, w)

			writeApiResponse(w, musebot.LoggedInApiResponse{username})
		} else {
			writeApiResponse(w, wrapApiError(errors.New("The username or password was incorrect.")))
		}

	})

	http.HandleFunc("/api/masquerade/", func(w http.ResponseWriter, r *http.Request) {
		if r.TLS == nil {
			writeApiResponse(w, wrapApiError(errors.New("This method requires TLS! :<")))
			return
		}

		sess := getSession(r)

		if !enforceLoggedIn(sess, w) {
			return
		}

		if !isSessionBool(sess, "administrator") {
			writeApiResponse(w, wrapApiError(errors.New("You're not an administrator!")))
			return
		}

		queryStrMap := r.URL.Query()
		qArray, ok := queryStrMap["username"]
		if !ok || len(qArray) < 1 || len(qArray[0]) == 0 {
			writeApiResponse(w, wrapApiError(errors.New("You must pass a 'username' argument specifying the user to masquerade as!")))
			return
		}

		q := qArray[0]

		sess.Values["logged-in"] = true
		sess.Values["username"] = q
		sess.Values["administrator"] = true

		sess.Save(r, w)

		w.Write([]byte("YOU ARE NOW LOGGED IN AS "))
		w.Write([]byte(q))

	})

	registerWsHandler()

	if len(cfg.ListenAddr) != 0 {
		httpServer := &http.Server{Addr: cfg.ListenAddr}
		go func() {
			log.Fatalln(httpServer.ListenAndServe())
		}()
		log.Println(" - HTTP Server is listening on", cfg.ListenAddr)
	}

	if len(cfg.SslListenAddr) == 0 {
		log.Fatalln(" x The HTTPS server *must* run. Login will only take place over HTTPS.")
	}
	httpsServer := &http.Server{Addr: cfg.SslListenAddr}
	go func() {
		log.Fatalln(httpsServer.ListenAndServeTLS("ssl.pub.pem", "ssl.priv.pem"))
	}()
	log.Println(" - HTTPS Server is listening on", cfg.SslListenAddr)
}
Ejemplo n.º 22
0
package store

import (
	"code.google.com/p/gorilla/sessions"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"net/http"
	"time"
)

var Database *mgo.Database
var Sessions = sessions.NewCookieStore([]byte("some-secret-keys"))

func init() {
	session, err := mgo.Dial("localhost")
	if err != nil {
		panic(err)
	}
	Database = session.DB("gopages-sample")
	//create an index for the username field on the users collection
	if err := Database.C("users").EnsureIndex(mgo.Index{
		Key:    []string{"username"},
		Unique: true,
	}); err != nil {
		panic(err)
	}
}

type User struct {
	Username string
	Password string
Ejemplo n.º 23
0
Archivo: web.go Proyecto: zond/wildlife
	w.Header().Set("Content-Type", "application/json")
	encoder := json.NewEncoder(w)
	if err := encoder.Encode(response); err != nil {
		panic(fmt.Errorf("While trying to encode %v: %v", response, err))
	}
}

func load(w http.ResponseWriter, r *http.Request) {
	render(w, r, getCells(r))
}

var htmlTemplates = template.Must(template.New("html").ParseGlob("templates/*.html"))
var jsTemplates = textTemplate.Must(textTemplate.New("js").ParseGlob("templates/*.js"))
var cssTemplates = textTemplate.Must(textTemplate.New("js").ParseGlob("templates/*.css"))

var sessionStore = sessions.NewCookieStore([]byte("wildlife in africa, we've got lions"))

func bg(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "image/png")
	image, err := os.Open("images/gophers.png")
	if err != nil {
		panic(fmt.Errorf("While trying to open background image: %v", err))
	}
	_, err = io.Copy(w, image)
	if err != nil {
		panic(fmt.Errorf("While trying to send background image: %v", err))
	}
}

func js(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/javascript")
Ejemplo n.º 24
0
	"github.com/jmoiron/monet/conf"
	"github.com/jmoiron/monet/template"
)

type AdminPanel interface {
	Render() string
}

var Panels = []AdminPanel{}

func AddPanel(p AdminPanel) {
	Panels = append(Panels, p)
}

var adminBase = template.Base{Path: "admin/base.mandira"}
var CookieStore = sessions.NewCookieStore([]byte(conf.Config.SessionSecret))

func AttachAdmin(url string) {
	// auth
	web.Get(url+"login/", login)
	web.Post(url+"login/", login)
	web.Get(url+"logout/", logout)
	// users
	/*  too much unnecessary work?
	    web.Get(url + "users/", userList)
	    web.Get(url + "users/edit/(.*)", userEdit)
	    web.Get(url + "users/delete/(.*)", userDelete)
	    web.Get(url + "users/add/", userAdd)
	    web.Post(url + "users/add/", userAddPost)
	*/
	web.Get(url, adminIndex)
Ejemplo n.º 25
0
// +build !appengine

package tap

import (
	"code.google.com/p/gorilla/sessions"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os"
)

var (
	Session = sessions.NewCookieStore([]byte("go-tap-very-secret"))
)

func (s *Server) getUserData(screen_name string, r *http.Request) (u UserData, err error) {
	u, ok := s.UserData[screen_name]
	if !ok {
		switch s.ServerType {
		case 0:
		case 1:
			bin, err := ioutil.ReadFile(s.DataDir + screen_name + ".json")
			if err == nil {
				err = json.Unmarshal(bin, &u)
			}
		}
	}
	return
}