示例#1
0
// Validates that the user cookie is set up before calling the handler
// passed as parameter.
func ValidateAuth(h httputils.ContextHandler) httputils.ContextHandler {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		var (
			sessionData *SessionData
			err         error
			ok          bool
			cookieStore *sessions.CookieStore
			session     *sessions.Session
		)

		cookieStore, ok = ctx.Value("cookieStore").(*sessions.CookieStore)

		if !ok {
			return fmt.Errorf("validate auth: could not cast value as cookie store:", ctx.Value("cookieStore"))
		}

		session, err = cookieStore.Get(r, SessionCookieName)

		if err != nil {
			log.Println(err)
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return nil
		}

		sessionData, ok = session.Values["data"].(*SessionData)

		if !ok {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return nil
		}

		authenticatedContext := context.WithValue(ctx, "sessionData", sessionData)
		return h(authenticatedContext, w, r)
	}
}
示例#2
0
func receiveCode(w http.ResponseWriter, req *http.Request, config map[string]string, store *sessions.CookieStore, templates *template.Template) {
	session, _ := store.Get(req, config["SESSION_NAME"])
	context, _ := url.ParseQuery(req.URL.RawQuery)
	if code, ok := context["code"]; ok {
		auth_code := string(code[0])
		resp, _ := http.PostForm(API_URI+"/token/",
			url.Values{"client_id": {config["CLIENT_ID"]},
				"client_secret": {config["CLIENT_SECRET"]},
				"grant_type":    {"authorization_code"},
				"code":          {auth_code},
				"redirect_uri":  {config["REDIRECT_URI"]},
				"scope":         {config["scope"]},
			})
		defer resp.Body.Close()
		if resp.StatusCode == 200 {
			var t_res TokenResponse
			dec := json.NewDecoder(resp.Body)
			err := dec.Decode(&t_res)
			if err != nil {
				log.Printf(err.Error())
			} else {
				session.Values[config["SESSION_ACCESS_TOKEN_KEY"]] = t_res.AccessToken
				session.Save(req, w)
				http.Redirect(w, req, "/", 303)
			}
		}
	} else if error_type, ok := context["error"]; ok {
		fmt.Fprintf(w, "%s: %s", string(error_type[0]), string(context["error_description"][0]))
	}
}
示例#3
0
func LoginFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		loginJSON := map[string]int{"LoginStatus": networkErrStatus}
		id := req.PostFormValue("UserID")
		if id == "" {
			http.ServeFile(w, req, "DHUCourseChooseHTML/login.html")
			return
		}
		pw := req.PostFormValue("UserPassword")
		//TODO It should be a form value that come from the user request
		school := "DHU"
		DBsession := GetSession()
		defer DBsession.Close()
		cLogin := DBsession.DB(school).C("StudentInfo")
		name, err := validateLogin(id, pw, school, cLogin)
		switch err {
		case nil:
			name = url.QueryEscape(name)
			http.SetCookie(w, &http.Cookie{Name: "stuName", Value: name})
			session, _ := store.Get(req, "sessionid")
			session.Values["stuid"] = id
			session.Values["school"] = school
			session.Save(req, w)
			loginJSON["LoginStatus"] = successStatus
		case passwordErr:
			loginJSON["LoginStatus"] = passwordErrStatus
		}

		r.JSON(w, http.StatusOK, loginJSON)
	}
}
示例#4
0
// LoginPostHandler writes out login response
func LoginPostHandler(req *http.Request, w http.ResponseWriter, cs *sessions.CookieStore, cfg *Config, connection *Connection) {
	username := req.PostFormValue("username")
	password := cryptPassword(req.PostFormValue("password"), cfg.SecretKey)

	var response []interface{}

	response, err := connection.LoginPost(username, password)

	if err != nil || len(response) == 0 {
		WriteJSONResponse(200, true, "Invalid username or password.", req, w)
	} else {
		// Store session
		userID := response[0].(map[string]interface{})["id"].(string)
		session := Session{UserID: userID,
			Expires: time.Now().Unix() + int64(cfg.SessionExpires)}

		response, err := connection.LoginPostInsertSession(session)

		if err != nil || response.Inserted < 1 {
			WriteJSONResponse(200, true, "Error creating the user session.", req, w)
		} else {
			session, _ := cs.Get(req, "magnet_session")
			session.Values["session_id"] = response.GeneratedKeys[0]
			session.Values["username"] = username
			session.Values["user_id"] = userID
			session.Save(req, w)
			WriteJSONResponse(200, false, "User correctly logged in.", req, w)
		}
	}
}
示例#5
0
func logged(r *http.Request, store *sessions.CookieStore) bool {
	session, _ := store.Get(r, "session-name")
	if _, ok := session.Values["login"]; ok {
		return true
	}
	return false
}
示例#6
0
文件: auth.go 项目: vichetuc/carton
func registerHandler(db db.DbManager, jar *sessions.CookieStore) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			session, _ := jar.Get(r, "carton-session")
			if _, ok := session.Values["user"]; ok {
				http.Error(w, "already signed in", http.StatusBadRequest)
				return
			}

			decoder := json.NewDecoder(r.Body)
			var user NewUser
			err := decoder.Decode(&user)
			if err != nil {
				http.Error(w, "error decoding json", http.StatusBadRequest)
				return
			}

			if user.Username == "" ||
				user.Password1 == "" ||
				user.Password2 == "" ||
				user.Password1 != user.Password2 {
				http.Error(w, "bad arguments", http.StatusBadRequest)
				return
			}

			if db.IsUser(user.Username) {
				http.Error(w, "user already exists", http.StatusBadRequest)
				return
			}

			bytePass := []byte(user.Password1)
			hash, err := bcrypt.GenerateFromPassword(bytePass, bcrypt.DefaultCost)
			if err != nil {
				http.Error(
					w,
					"error hashing password",
					http.StatusInternalServerError,
				)
				return
			}

			err = db.RegisterUser(user.Username, hash)
			if err != nil {
				http.Error(
					w,
					"unable to add user",
					http.StatusInternalServerError,
				)
				return
			}
			session.Values["user"] = user.Username
			session.Save(r, w)
			w.WriteHeader(http.StatusCreated)
			fmt.Fprintf(w, "Successfully registered %v", user.Username)
		} else {
			return404(w)
		}
	})
}
示例#7
0
文件: middleware.go 项目: ab22/abcd
// ValidateAuth validates that the user cookie is set up before calling the
// handler passed as parameter.
func ValidateAuth(h httputils.ContextHandler) httputils.ContextHandler {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		var (
			sessionData *httputils.SessionData
			err         error
			ok          bool
			cookieStore *sessions.CookieStore
			session     *sessions.Session
			cfg         = ctx.Value("config").(*config.Config)
		)

		cookieStore, ok = ctx.Value("cookieStore").(*sessions.CookieStore)

		if !ok {
			httputils.WriteError(w, http.StatusInternalServerError, "")
			return fmt.Errorf("validate auth: could not cast value as cookie store: %s", ctx.Value("cookieStore"))
		}

		session, err = cookieStore.Get(r, cfg.SessionCookieName)

		if err != nil {
			log.Println(err)
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return nil
		}

		sessionData, ok = session.Values["data"].(*httputils.SessionData)

		if !ok || sessionData.IsInvalid() {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return nil
		} else if time.Now().After(sessionData.ExpiresAt) {
			session.Options.MaxAge = -1
			session.Save(r, w)
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)

			return nil
		}

		// Extend the session's lifetime.
		cfg, ok = ctx.Value("config").(*config.Config)

		if !ok {
			httputils.WriteError(w, http.StatusInternalServerError, "")
			return fmt.Errorf("validate auth: error casting config object: %s", ctx.Value("config"))
		}

		// Save session only if the session was extended.
		if extendSessionLifetime(sessionData, cfg.SessionLifeTime) {
			sessionData.ExpiresAt = time.Now().Add(cfg.SessionLifeTime)
			session.Save(r, w)
		}

		authenticatedContext := context.WithValue(ctx, "sessionData", sessionData)
		return h(authenticatedContext, w, r)
	}
}
示例#8
0
// LogoutHandler writes out logout response
func LogoutHandler(cs *sessions.CookieStore, req *http.Request, connection *Connection, w http.ResponseWriter) {
	session, _ := cs.Get(req, "magnet_session")

	_, _ = connection.Logout(session)

	session.Values["user_id"] = ""
	session.Values["session_id"] = ""
	session.Values["username"] = ""
	session.Save(req, w)

	http.Redirect(w, req, "/", 301)
}
示例#9
0
文件: users.go 项目: patrickjr/poker2
func logout(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore, t *template.Template) {
	s, _ := store.Get(r, "rp-session")
	if s.IsNew {
		http.Redirect(w, r, "/", 200)
	}
	//s.Options.MaxAge = -1
	user := s.Values["user"].(*users.User)
	user.Logout(db)
	s.Values["user"] = users.Default
	http.SetCookie(w, &http.Cookie{Name: "rp-session", MaxAge: -1, Path: "/"})
	http.Redirect(w, r, "/", 200)
}
示例#10
0
// Session attaches session to gin context
func Session(store *sessions.CookieStore) gin.HandlerFunc {
	return func(c *gin.Context) {
		session, err := store.Get(c.Request, utils.ConfigEntry("SessionName"))
		if err != nil {
			tracelog.CompletedError(err, "Session", "Getting the session")
			c.Error(err, "Failed to create session")
			c.AbortWithStatus(500)
		}

		c.Set("session", session)
		defer context.Clear(c.Request)
	}
}
示例#11
0
文件: auth.go 项目: vichetuc/carton
func loginHandler(db db.DbManager, jar *sessions.CookieStore) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			session, _ := jar.Get(r, "carton-session")
			if _, ok := session.Values["user"]; ok {
				http.Error(w, "already signed in", http.StatusBadRequest)
				return
			}

			decoder := json.NewDecoder(r.Body)
			var user User
			err := decoder.Decode(&user)
			if err != nil {
				http.Error(w, "error decoding json", http.StatusBadRequest)
				return
			}

			if user.Username == "" || user.Password == "" {
				http.Error(w, "bad arguments", http.StatusBadRequest)
				return
			}

			dbHash := db.GetPwdHash(user.Username)
			if dbHash == nil {
				http.Error(
					w,
					"user password combo doesn't exist",
					http.StatusBadRequest,
				)
				return
			}

			err = bcrypt.CompareHashAndPassword(dbHash, []byte(user.Password))
			if err != nil {
				http.Error(
					w,
					"user password combo doesn't exist",
					http.StatusBadRequest,
				)
				return
			}
			session.Values["user"] = user.Username
			session.Save(r, w)
			// Sets return code to 200
			fmt.Fprintln(w, "login succeeded")
		} else {
			return404(w)
		}
	})
}
示例#12
0
文件: auth.go 项目: vichetuc/carton
func statusHandler(jar *sessions.CookieStore) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			session, _ := jar.Get(r, "carton-session")
			if _, ok := session.Values["user"]; ok {
				// Sets return code to 200
				fmt.Fprintln(w, "User is logged in")
			} else {
				http.Error(w, "No user is signed in", http.StatusForbidden)
			}
		} else {
			return404(w)
		}
	})
}
示例#13
0
func StreamCreateMiddleware(cs *sessions.CookieStore, ss *ssemux.Store) routing.Handler {
	return func(c *routing.Context) error {
		// Get a session. We're ignoring the error resulted from decoding an
		// existing session: Get() always returns a session, even if empty.
		session, err := cs.Get(c.Request, SESSION_NAME)
		if err != nil {
			return routing.NewHTTPError(http.StatusInternalServerError, err.Error())
		}
		fmt.Println("id:  " + session.Values["id"].(string))
		fmt.Println("uid: " + session.Values["uid"].(string))
		c.Set(STREAM_CONTEXT_KEY, ss.New(session.Values["id"].(string)))
		ss.Associate(session.Values["id"].(string), "uid", session.Values["uid"].(string))
		return nil
	}
}
func CookieMiddleware(c *sessions.CookieStore) MiddlewareFunc {
	//That Middleware is used to detect the session
	return func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		urlpath := r.URL.Path
		if _, ok := UrlNotDetectSessionList[urlpath]; !ok {
			session, _ := c.Get(r, "sessionid")
			if session.IsNew || session.Values["stuid"] == "" {
				next(rw, r)
				http.Redirect(rw, r, "/index", http.StatusMovedPermanently)
				return
			}
		}
		next(rw, r)
	}
}
示例#15
0
文件: util.go 项目: gauthierc/magnet
// GetUserID fetches userID from rethinkdb
func GetUserID(cs *sessions.CookieStore, req *http.Request, connection *Connection) string {
	session, _ := cs.Get(req, "magnet_session")
	var response map[string]interface{}

	userID := ""

	response, err := connection.GetUnexpiredSession(session)

	if err == nil && len(response) > 0 {
		if int64(response["Expires"].(float64)) > time.Now().Unix() {
			userID = response["UserID"].(string)
		}
	}

	return userID
}
示例#16
0
func SessionMiddleware(cs *sessions.CookieStore) routing.Handler {
	return func(c *routing.Context) error {
		session, err := cs.Get(c.Request, SESSION_NAME)
		if err != nil {
			return routing.NewHTTPError(http.StatusInternalServerError, err.Error())
		}
		if session.IsNew {
			randId, _ := rand.Int(rand.Reader, big.NewInt(100000))
			randInt, _ := rand.Int(rand.Reader, big.NewInt(3))
			session.Values["id"] = randId.String()
			session.Values["uid"] = randInt.String()
		}
		session.Save(c.Request, c.Response)
		return nil
	}
}
示例#17
0
文件: users.go 项目: patrickjr/poker2
func checkSession(r *http.Request, db *sql.DB, s *sessions.CookieStore) (*users.User, bool) {
	exists, _ := s.Get(r, "rp-session")
	if exists.IsNew {
		return nil, false
	} else {
		x := exists.Values["user"]
		if x != nil {
			user := x.(*users.User)
			err := loginWithCookie(db, user.Name, "", r.RemoteAddr)
			if err != nil {
				return nil, false
			}
			return user, true
		}
		return nil, false
	}
}
示例#18
0
文件: auth.go 项目: vichetuc/carton
func logoutHandler(jar *sessions.CookieStore) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			session, _ := jar.Get(r, "carton-session")
			if _, ok := session.Values["user"]; !ok {
				http.Error(w, "no user to sign out", http.StatusBadRequest)
				return
			}
			delete(session.Values, "user")
			session.Save(r, w)
			// Sets return code to 200
			fmt.Fprintln(w, "Successfully logged out")
		} else {
			return404(w)
		}
	})
}
示例#19
0
//function that returns true if the client is authenticated (has a valid cookie)
//also returns the session information associated with the cookie
func confirmSession(store *sessions.CookieStore, errorMsg string, w http.ResponseWriter, r *http.Request) (bool, *sessions.Session) {
	//check for session to see if client is authenticated
	session, err := store.Get(r, "flash-session")
	if err != nil {
		//http.Error(w, err.Error(), http.StatusInternalServerError)
		handleError(err, errorMsg, w)
		return false, nil
	}
	fm := session.Flashes("message")
	if fm == nil {
		//fmt.Fprint(w, "No flash messages")
		handleError(err, errorMsg, w)
		return false, nil
	}
	//session.Save(r, w)

	return true, session
}
示例#20
0
func getStream(store *sessions.CookieStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		session, _ := store.Get(r, "sndcld")

		t, ok := session.Values["token"]
		if !ok {
			http.Error(w, "No token in session", 500)
		}

		resp, err := http.Get(fmt.Sprintf("https://api.soundcloud.com/me/activities?limit=25&oauth_token=%s", t.(string)))
		if err != nil {
			http.Error(w, "No token in session", 500)
		}
		defer resp.Body.Close()

		io.Copy(w, resp.Body)
	}
}
示例#21
0
文件: users.go 项目: patrickjr/poker2
func login(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore, t *template.Template) {
	if r.Method == "POST" {
		r.ParseForm()
		username, password, remember := r.FormValue("user[name]"), r.FormValue("user[password]"), r.FormValue("user[remember_me]")
		User, err := users.Login(db, username, password, remember, r.RemoteAddr)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		s, _ := store.Get(r, "rp-session")
		setSessionOpts(r, User, s)
		s.Values["user"] = User
		err = s.Save(r, w)
		if err != nil {
			fmt.Println(err)
		}
		renderTemplate(w, "user_nav_info", t, User)
	}
}
示例#22
0
文件: friends.go 项目: bsliu17/Explor
func CheckSession(w http.ResponseWriter, r *http.Request, store *sessions.CookieStore) string {

	//check for session to see if client is authenticated
	session, err := store.Get(r, "flash-session")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	fm := session.Flashes("message")
	if fm == nil {
		fmt.Println("Trying to vote on forum thread as an invalid user")
		fmt.Fprint(w, "No flash messages")
		w.WriteHeader(http.StatusUnauthorized)
		return ""
	}

	//get the user id and username from the cookie
	userId := session.Values["userid"].(int)

	return strconv.Itoa(userId)
}
示例#23
0
func index(w http.ResponseWriter, req *http.Request, config map[string]string, store *sessions.CookieStore, templates *template.Template) {
	session, _ := store.Get(req, config["SESSION_NAME"])
	token, ok := session.Values[config["SESSION_ACCESS_TOKEN_KEY"]]
	if !ok {
		context := map[string]string{
			"path":         req.URL.Path,
			"client_id":    config["CLIENT_ID"],
			"scope":        config["scope"],
			"redirect_uri": config["REDIRECT_URI"],
		}
		_ = templates.ExecuteTemplate(w, "index", context)
	} else {
		access_token, _ := token.(string)
		data, status := JSONResponse("GET", API_URI+"/1/names/", access_token)
		if status != 200 {
			// Probably, the auth code expired. Go back home and re-authenticate.
			delete(session.Values, config["SESSION_ACCESS_TOKEN_KEY"])
			session.Save(req, w)
			http.Redirect(w, req, "/", 303)
		}
		var names NamesResponse
		var genotypes []Genome
		err := json.Unmarshal(data, &names)
		data, status = JSONResponse("GET", API_URI+"/1/genotype/?locations="+config["genotype_scopes"], access_token)
		err = json.Unmarshal(data, &genotypes)
		if err != nil {
			log.Printf(err.Error())
		}
		names_by_profile := namesByProfile(&names)
		var boneStrengthProfiles []BoneStrengthProfile
		for _, genotype := range genotypes {
			boneStrength := computeBoneStrength(&genotype)
			boneStrengthProfile := BoneStrengthProfile{
				BoneStrength: boneStrength,
				Name:         names_by_profile[genotype.Id],
			}
			boneStrengthProfiles = append(boneStrengthProfiles, boneStrengthProfile)
		}
		_ = templates.ExecuteTemplate(w, "result", boneStrengthProfiles)
	}
}
示例#24
0
func validateSession(req *http.Request, store *sessions.CookieStore) (sessionid, schoolid string, flag bool) {
	session, _ := store.Get(req, "sessionid")
	id := session.Values["stuid"]
	school := session.Values["school"]
	schooln, ok := school.(string)
	if ok {
		_, ok := SchoolStructs[schooln]
		if !ok {
			return
		}
	} else {
		return
	}
	stringid, ok := id.(string)
	if ok && stringid != "" {
		sessionid = stringid
		schoolid = schooln
		flag = true
	}
	return
}
示例#25
0
func handleOAuth2Callback(store *sessions.CookieStore, config *oauth2.Config, token string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if st := r.FormValue("state"); st != token {
			http.Error(w, "Returned state token does not match.", 401)
		}

		t, err := config.Exchange(oauth2.NoContext, r.FormValue("code"))
		if err != nil {
			http.Error(w, err.Error(), 500)
		}

		session, _ := store.Get(r, "sndcld")

		session.Values["token"] = t.AccessToken
		session.Save(r, w)

		f, _ := os.Open("./layout.html")
		io.Copy(w, f)
		f.Close()
	}
}
示例#26
0
文件: server.go 项目: bsliu17/app
//handle the chat event which checks if the cookie corresponds to a logged in user and adds the user to the chat room
//TODO: Return correct status and message if session is invalid
func chattingRoom(w http.ResponseWriter, r *http.Request, store *sessions.CookieStore, room *chat.ChatRoom) {

	//check for session to see if client is authenticated
	session, err := store.Get(r, "flash-session")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	fm := session.Flashes("message")
	if fm == nil {
		fmt.Println("Trying to log in as invalid user")
		fmt.Fprint(w, "No flash messages")
		return
	}
	//session.Save(r, w)

	fmt.Println("New user connected to chat")

	//use the id and username attached to the session to create the player
	// chatterHandler := ChatterHandler{Id: session.Values["userid"].(int), Username: session.Values["username"].(string), Room: room}

	chat.CreateChatter(w, r, session.Values["userid"].(int), session.Values["username"].(string), room)
}
示例#27
0
文件: auth.go 项目: andrew-li/Greddit
//function that authenticates/signs in user
func loginHandler(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore) {

	fmt.Println("Authenticating user...")

	//add headers to response
	addWriteHeaders(&w, r)

	//ignore options requests
	if handleOptionsRequests(w, r) == true {
		return
	}

	//parse the request body into a map
	dat, ok := parseJsonRequest(w, r)
	if ok == false {
		return
	}

	//get username and password
	username := dat["username"].(string)
	password := dat["password"].(string)

	//variable(s) to hold the returned values from the query
	var (
		queried_user_id       int
		queried_password_hash string
	)

	//query the database for the username
	err := db.QueryRow("select user_id, password_hash from users where user_name = ?", username).Scan(&queried_user_id, &queried_password_hash)
	switch {

	//if username doesn't exist
	case err == sql.ErrNoRows:
		handleError(err, "Username cannot be found", w)
		break

	//if error querying database
	case err != nil:
		handleError(err, "Error querying database", w)
		break

	//if username exists
	default:
		//fmt.Println("Retrieved User Id is %d\n", queried_user_id)
		//fmt.Println("Retrieved Password is %s\n", queried_password_hash)

		//compare the retrieved password to the password sent by the client
		err := bcrypt.CompareHashAndPassword([]byte(queried_password_hash), []byte(password))
		if err != nil {
			//password not a match
			handleError(err, "Password incorrect", w)
		} else {
			//user is authorized

			//create session
			session, err := store.Get(r, "flash-session")
			if err != nil {
				handleError(err, "Error creating session", w)
				return
			}
			session.Values["userid"] = queried_user_id
			session.Values["username"] = username
			session.AddFlash("This is a flashed message!", "message")
			session.Save(r, w)

			//return 200 status to indicate success
			fmt.Println("about to write 200 header")
			fmt.Println("password correct")
			w.WriteHeader(http.StatusOK)
		}
		break

	}

}
示例#28
0
//TODO: Return correct status and message if session is invalid
//TODO: Return correct status and message if insert failed
//TODO: format retrieved datetime to javascript datetime
func CreateForumThread(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore) {

	fmt.Println("Creating forum thread...")

	//add headers to response
	w.Header()["access-control-allow-origin"] = []string{"http://localhost:8080"} //TODO: fix this?
	w.Header()["access-control-allow-methods"] = []string{"GET, POST, OPTIONS"}
	w.Header()["Content-Type"] = []string{"application/json"}

	//ignore options requests
	if r.Method == "OPTIONS" {
		fmt.Println("options request received")
		w.WriteHeader(http.StatusTemporaryRedirect)
		return
	}

	//check for session to see if client is authenticated
	session, err := store.Get(r, "flash-session")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	fm := session.Flashes("message")
	if fm == nil {
		fmt.Println("Trying to create a thread as an invalid user")
		fmt.Fprint(w, "No flash messages")
		return
	}
	//session.Save(r, w)

	//get the user id and username from the cookie
	userid := session.Values["userid"].(int)
	//username := session.Values["username"].(string)

	//parse the body of the request into a string
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(err)
	}
	//fmt.Println(string(body))

	//parse the JSON string body to get the forum thread info
	byt := body
	var dat map[string]interface{}
	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}
	thread_title := dat["title"].(string)
	thread_body := dat["body"].(string)

	var thread_link string
	if _, ok := dat["link"]; ok {
		thread_link = dat["link"].(string)
	}

	var thread_tag string
	if _, ok := dat["tag"]; ok {
		thread_tag = dat["tag"].(string)
	}

	var thread_longitude float64
	if _, ok := dat["lng"]; ok {
		thread_longitude = dat["lng"].(float64)
	}

	var thread_latitude float64
	if _, ok := dat["lat"]; ok {
		thread_latitude = dat["lat"].(float64)
	}

	//TODO: handle lat and long passed in as non float types

	//insert forum thread into database
	stmt, err := db.Prepare("insert into forum_threads (user_id, title, body, link, tag, longitude, latitude) values (?, ?, ?, ?, ?, ?, ?)")
	if err != nil {
		log.Fatal(err)
	}
	res, err := stmt.Exec(userid, thread_title, thread_body, thread_link, thread_tag, thread_longitude, thread_latitude)
	if err != nil {
		log.Fatal(err)
	}
	lastId, err := res.LastInsertId()
	if err != nil {
		log.Fatal(err)
	}
	rowCnt, err := res.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Inserted thread "+thread_title+" into database. Last inserted ID = %d, rows affected = %d\n", lastId, rowCnt)

	//return 200 status to indicate success
	fmt.Println("about to write 200 header")
	w.Write([]byte("{\"thread_id\" : " + strconv.FormatInt(lastId, 10) + "}"))
}
示例#29
0
//TODO: Return correct status and message if session is invalid
//TODO: Return correct status and message if query failed
func DeleteForumThread(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore, id int) {

	fmt.Println("Delete forum thread...")

	//add headers to response
	w.Header()["access-control-allow-origin"] = []string{"http://localhost:8080"} //TODO: fix this?
	w.Header()["access-control-allow-methods"] = []string{"GET, POST, OPTIONS"}
	w.Header()["Content-Type"] = []string{"application/json"}

	//ignore options requests
	if r.Method == "OPTIONS" {
		fmt.Println("options request received")
		w.WriteHeader(http.StatusTemporaryRedirect)
		return
	}

	//check for session to see if client is authenticated
	session, err := store.Get(r, "flash-session")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	fm := session.Flashes("message")
	if fm == nil {
		fmt.Println("Trying to delete forum thread as an invalid user")
		fmt.Fprint(w, "No flash messages")
		return
	}
	//session.Save(r, w)

	//get the user id and username from the cookie
	userid := session.Values["userid"].(int)

	var (
		queried_user_id int
	)

	//don't delete the thread if the user was not the one who created it
	err = db.QueryRow("select user_id from forum_threads where thread_id = ?", id).Scan(&queried_user_id)
	switch {

	//if thread doesn't exist
	case err == sql.ErrNoRows:
		//return 400 status to indicate error
		fmt.Println("about to write 400 header")
		fmt.Println("Thread cannot be found")
		w.Write([]byte(fmt.Sprintf("Thread cannot be found")))
		return
		//break

	//if error querying database
	case err != nil:
		log.Fatal(err)
		//return 400 status to indicate error
		fmt.Println("about to write 400 header")
		w.Write([]byte(fmt.Sprintf("Error querying database")))
		return
		//break

	//if thread exists
	default:
		if queried_user_id != userid {
			fmt.Println("about to write 400 header")
			fmt.Println("Cannot delete another user's thread")
			w.Write([]byte(fmt.Sprintf("Cannot delete another user's thread")))
			return
		}
		break

	}

	//TODO: return error if thread id is blank/nan

	//delete all votes related to forum posts
	stmt, err := db.Prepare("delete post_votes from post_votes inner join thread_posts on post_votes.post_id = thread_posts.post_id where thread_posts.thread_id = ?")

	if err != nil {
		log.Fatal(err)
	}
	res, err := stmt.Exec(id)
	if err != nil {
		log.Fatal(err)
	}
	rowCnt, err := res.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Deleted votes for forum posts with forum thread id "+strconv.Itoa(id)+". Rows affected = %d\n", rowCnt)

	//delete all forum posts related to the forum thread
	stmt, err = db.Prepare("delete from thread_posts where thread_id = ?")
	if err != nil {
		log.Fatal(err)
	}
	res, err = stmt.Exec(id)
	if err != nil {
		log.Fatal(err)
	}
	rowCnt, err = res.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Deleted forum posts with forum thread id "+strconv.Itoa(id)+". Rows affected = %d\n", rowCnt)

	//delete all votes related to the forum thread
	stmt, err = db.Prepare("delete from thread_votes where thread_id = ?")

	if err != nil {
		log.Fatal(err)
	}
	res, err = stmt.Exec(id)
	if err != nil {
		log.Fatal(err)
	}
	rowCnt, err = res.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Deleted votes for forum thread with id "+strconv.Itoa(id)+". Rows affected = %d\n", rowCnt)

	//delete the forum thread
	stmt, err = db.Prepare("delete from forum_threads where thread_id = ?")
	if err != nil {
		log.Fatal(err)
	}
	res, err = stmt.Exec(id)
	if err != nil {
		log.Fatal(err)
	}
	rowCnt, err = res.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Deleted forum thread "+strconv.Itoa(id)+". Rows affected = %d\n", rowCnt)

	//return 200 status to indicate success
	fmt.Println("about to write 200 header")
	w.WriteHeader(http.StatusOK)

}
示例#30
0
//TODO: Return correct status and message if session is invalid
//TODO: Return correct status and message if query failed
func EditForumThread(w http.ResponseWriter, r *http.Request, db *sql.DB, store *sessions.CookieStore) {

	fmt.Println("Edit forum thread...")

	//add headers to response
	w.Header()["access-control-allow-origin"] = []string{"http://localhost:8080"} //TODO: fix this?
	w.Header()["access-control-allow-methods"] = []string{"GET, POST, OPTIONS"}
	w.Header()["Content-Type"] = []string{"application/json"}

	//ignore options requests
	if r.Method == "OPTIONS" {
		fmt.Println("options request received")
		w.WriteHeader(http.StatusTemporaryRedirect)
		return
	}

	//check for session to see if client is authenticated
	session, err := store.Get(r, "flash-session")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	fm := session.Flashes("message")
	if fm == nil {
		fmt.Println("Trying to edit forum thread as an invalid user")
		fmt.Fprint(w, "No flash messages")
		return
	}
	//session.Save(r, w)

	//get the user id and username from the cookie
	userid := session.Values["userid"].(int)

	//parse the body of the request into a string
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(err)
	}
	//fmt.Println(string(body))

	//parse the JSON string body to get the forum thread info
	byt := body
	var dat map[string]interface{}
	if err := json.Unmarshal(byt, &dat); err != nil {
		panic(err)
	}
	thread_id := int(dat["thread_id"].(float64))
	thread_title := dat["title"].(string)
	thread_body := dat["body"].(string)
	thread_link := dat["link"].(string)
	thread_tag := dat["tag"].(string)
	thread_longitude := dat["lng"].(float64)
	thread_latitude := dat["lat"].(float64)

	var (
		queried_user_id int
	)

	//don't edit the thread if the user was not the one who created it
	err = db.QueryRow("select user_id from forum_threads where thread_id = ?", thread_id).Scan(&queried_user_id)
	switch {

	//if thread doesn't exist
	case err == sql.ErrNoRows:
		//return 400 status to indicate error
		fmt.Println("about to write 400 header")
		fmt.Println("Thread cannot be found")
		w.Write([]byte(fmt.Sprintf("Thread cannot be found")))
		return
		//break

	//if error querying database
	case err != nil:
		log.Fatal(err)
		//return 400 status to indicate error
		fmt.Println("about to write 400 header")
		w.Write([]byte(fmt.Sprintf("Error querying database")))
		return
		//break

	//if thread exists
	default:
		if queried_user_id != userid {
			fmt.Println("about to write 400 header")
			fmt.Println("Cannot edit another user's thread")
			w.Write([]byte(fmt.Sprintf("Cannot edit another user's thread")))
			return
		}
		break

	}

	//TODO: return error if thread id is blank/nan

	//update the forum thread post
	stmt, err := db.Prepare("update forum_threads set title = ?, body = ?, link = ?, tag = ?, longitude = ?, latitude = ? where thread_id = ?")
	if err != nil {
		log.Fatal(err)
	}
	res, err := stmt.Exec(thread_title, thread_body, thread_link, thread_tag, thread_longitude, thread_latitude, thread_id)
	if err != nil {
		log.Fatal(err)
	}
	rowCnt, err := res.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Updated contents of forum thread "+strconv.Itoa(thread_id)+". Rows affected = %d\n", rowCnt)

	//return 200 status to indicate success
	fmt.Println("about to write 200 header")
	w.WriteHeader(http.StatusOK)

}