Example #1
0
func CheckAuth(w http.ResponseWriter, r *http.Request) {
	var params = r.URL.Query()
	if check := params.Get("check"); len(check) > 0 {
		w.WriteHeader(http.StatusOK)
		return
	}
	var hash = params.Get("hash")
	if len(hash) == 0 {
		util.Error(errors.New("No hash supplied for auth."), w)
		return
	}
	data, err := base64.StdEncoding.DecodeString(hash)
	if err != nil {
		util.Error(err, w)
		return
	}
	args := strings.Split(string(data), ":")

	if len(args) == 2 {
		if checkUserIn(args[0], args[1], w, r) {
			w.WriteHeader(http.StatusOK)
		} else {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	} else {
		util.Error(errors.New("Unable to authenticate."), w)
	}
}
Example #2
0
File: links.go Project: jawr/wall
func Search(w http.ResponseWriter, r *http.Request, params url.Values, limit, offset int) {
	session, err := auth.GetSession(r)
	if err != nil {
		util.Error(err, w)
		return
	}
	userID := r.URL.Query().Get("user_id")
	if len(userID) > 0 {
		user, err := users.GetByID(userID)
		if err != nil {
			util.Error(err, w)
			return
		}
		query := r.URL.Query().Get("query")
		res, err := db.Search(user, query)
		util.ToJSON(res, err, w)
		return
	} else {
		var user users.User
		if u, ok := session.Values["user"]; ok {
			user = u.(users.User)
			log.Println(user)
			query := r.URL.Query().Get("query")
			res, err := db.Search(user, query)
			util.ToJSON(res, err, w)
			return
		}
	}
	util.Error(errors.New("Unable to get session"), w)
}
Example #3
0
File: links.go Project: jawr/wall
func Create(w http.ResponseWriter, r *http.Request) {
	var o db.Link
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&o)
	if err != nil {
		util.Error(err, w)
		return
	}
	err = o.Insert()
	if err != nil {
		util.Error(err, w)
		return
	}
	err = o.Load()
	if err != nil {
		util.Error(err, w)
		return
	}
	linkURL, err := url.Parse(o.URL)
	if err != nil {
		util.Error(err, w)
		return
	}
	err = o.AddTag(linkURL.Host)
	util.ToJSON(o, err, w)
}
Example #4
0
/*
	Search is used for retrieving records for a domain. It accepts the following
	GET params:

	+ duuid 	- uuid of domain
	+ domain	- string of domain
	+ name		- string of name

*/
func Search(w http.ResponseWriter, r *http.Request, params url.Values, limit, offset int) {
	query := db.SELECT
	var where []string
	var args []interface{}
	i := 1
	for k, _ := range params {
		switch k {
		case "name":
			where = append(where, fmt.Sprintf(k+" = $%d", i))
			args = append(args, params.Get(k))
			i++
		case "duuid", "domain":
			where = append(where, fmt.Sprintf("domain = $%d", i))
			args = append(args, params.Get(k))
			v := params.Get(k)
			params.Del("duuid")
			params.Del("domain")
			params.Set("domain", v)
			i++
		}
	}
	if len(where) > 0 {
		query += "WHERE " + strings.Join(where, " AND ") + " "
	}
	query += fmt.Sprintf("ORDER BY added DESC LIMIT $%d OFFSET $%d", len(args)+1, len(args)+2)
	args = append(args, limit, offset)
	log.Info("Query: " + query)
	log.Info("Args: %+v", args)
	recordList, err := db.GetList(query, args...)
	if err != nil {
		util.Error(err, w)
		return
	}
	// check for none sql errors
	// if we have no results dispatch a worker to get one
	if len(recordList) == 0 {
		// no domain lets grab one using what we assume is a duuid
		log.Info("no records")
		if duuid := params.Get("domain"); duuid != "" {
			log.Info("duuid: " + duuid)
			domain, err := domains.GetByUUID(duuid).One()
			if err != nil {
				log.Info("herererere")
				util.Error(err, w)
				return
			}
			results := <-dispatcher.AddDomain(domain)
			log.Info("%v", results)
			for _, result := range results {
				recordList = append(recordList, result)
			}
		}
	}
	util.ToJSON(cleanParserFromRecords(recordList), err, w)
}
Example #5
0
File: links.go Project: jawr/wall
func Save(w http.ResponseWriter, r *http.Request) {
	var o db.Link
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&o)
	if err != nil {
		util.Error(err, w)
		return
	}
	err = o.Save()
	if err != nil {
		util.Error(err, w)
		return
	}
	err = o.Load()
	util.ToJSON(o, err, w)
}
Example #6
0
File: auth.go Project: jawr/wall
func New(db *pgstore.Store) httpHandler {
	str = db
	cfg := config.Get()
	sessionName = cfg.GetString("session_name")
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				session, err := GetSession(r)
				if err != nil {
					log.Println("no session.")
					utils.Error(err, w)
					return
				}
				if t, ok := session.Values["expires"]; ok {
					if time.Now().Before(t.(time.Time)) {
						// authed
						var u users.User
						if _u, ok := session.Values["user"]; ok {
							u = _u.(users.User)
							w.Header().Set("X-User", u.ID)
						}
						w.Header().Set("X-Expires", t.(time.Time).Format("2006-01-02T15:04:05"))
						h.ServeHTTP(w, r)
						return
					}
				}
				h.ServeHTTP(w, r)

			},
		)
	}
}
Example #7
0
/*
	Search is used for retrieving watchers. It accepts the following
	GET params:

	+ duuid 	- uuid of domain
	+ domain	- string of domain
	+ name		- string of name

*/
func Search(w http.ResponseWriter, r *http.Request, params url.Values, limit, offset int) {
	query := db.SELECT
	var where []string
	var args []interface{}
	i := 1
	for k, _ := range params {
		switch k {
		case "user":
			user, err := auth.GetUser(r)
			if err != nil {
				util.Error(err, w)
				return
			}
			where = append(where, fmt.Sprintf("users@> '[%d]'", user.ID))
			i++
		case "name":
			where = append(where, fmt.Sprintf(k+" = $%d", i))
			args = append(args, params.Get(k))
			i++
		case "duuid", "domain":
			where = append(where, fmt.Sprintf("domain = $%d", i))
			args = append(args, params.Get(k))
			i++
		}
	}
	if len(where) > 0 {
		query += "WHERE " + strings.Join(where, " AND ") + " "
	}
	query += fmt.Sprintf("LIMIT $%d OFFSET $%d", len(args)+1, len(args)+2)
	args = append(args, limit, offset)
	log.Info("Query: " + query)
	log.Info("Args: %+v", args)
	watcherList, err := db.GetList(query, args...)
	util.ToJSON(watcherList, err, w)
}
Example #8
0
File: links.go Project: jawr/wall
func Refresh(w http.ResponseWriter, r *http.Request, res []db.Link) {
	err := res[0].Parse()
	if err != nil {
		util.Error(err, w)
		return
	}
	err = res[0].Save()
	util.ToJSON(res[0], err, w)
}
Example #9
0
func ByName(fn func(http.ResponseWriter, *http.Request, db.Domain)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		name, tld, err := tlds.DetectDomainAndTLD(vars["name"])
		if err != nil {
			util.Error(err, w)
			return
		}
		domain, err := db.GetByNameAndTLD(name, tld).One()
		if err != nil {
			domain = db.New(name, tld)
			err = domain.Insert()
			if err != nil {
				util.Error(err, w)
				return
			}
		}
		fn(w, r, domain)
	}
}
Example #10
0
File: links.go Project: jawr/wall
func GetByID(fn func(http.ResponseWriter, *http.Request, []db.Link)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		res, err := db.GetByID(util.ParseInt(vars["id"]))
		if err != nil {
			util.Error(err, w)
			return
		}
		fn(w, r, res)
	}
}
Example #11
0
File: links.go Project: jawr/wall
func RemoveTag(w http.ResponseWriter, r *http.Request, res []db.Link) {
	var tag string
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&tag)
	if err != nil {
		util.Error(err, w)
		return
	}
	err = res[0].RemoveTag(tag)
	util.ToJSON(res[0], err, w)
}
Example #12
0
func ByUUID(fn func(http.ResponseWriter, *http.Request, db.Domain)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		uuid := vars["uuid"]
		domain, err := db.GetByUUID(uuid).One()
		if err != nil {
			util.Error(err, w)
			return
		}
		fn(w, r, domain)
	}
}
Example #13
0
func Archive(w http.ResponseWriter, r *http.Request) {
	var post []db.Message
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&post)
	if err != nil {
		util.Error(err, w)
		return
	}
	user, err := auth.GetUser(r)
	if err != nil {
		util.Error(err, w)
		return
	}
	note, err := db.GetByUser(*user).One()
	if err != nil {
		util.Error(err, w)
		return
	}
	note.ArchiveMessages(post)
	util.ToJSON(post, nil, w)
}
Example #14
0
File: auth.go Project: jawr/wall
// Destroy a session
func Logout(w http.ResponseWriter, r *http.Request) {
	session, err := GetSession(r)
	if err != nil {
		utils.Error(err, w)
		return
	}

	if t, ok := session.Values["expires"]; ok {
		if time.Now().Before(t.(time.Time)) {
			session.Options.MaxAge = -1

			if err := str.Save(r, w, session); err != nil {
				utils.Error(err, w)
				return
			}

			w.WriteHeader(http.StatusOK)
			return
		}
	}
	w.WriteHeader(http.StatusUnauthorized)
}
Example #15
0
func Create(w http.ResponseWriter, r *http.Request) {
	var post struct {
		Domain   string `json:"domain"`
		Name     string `json:"name"`
		Interval string `json:"interval"`
	}
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&post)
	if err != nil {
		util.Error(err, w)
		return
	}
	var domain domains.Domain
	if len(post.Name) > 0 {
		name, tld, err := tlds.DetectDomainAndTLD(post.Name)
		if err != nil {
			util.Error(err, w)
			return
		}
		domain, err = domains.GetByNameAndTLD(name, tld).One()
		if err != nil {
			domain = domains.New(name, tld)
			err = domain.Insert()
			if err != nil {
				util.Error(err, w)
				return
			}
		}
	} else {
		domain, err = domains.GetByUUID(post.Domain).One()
		if err != nil {
			util.Error(err, w)
			return
		}
	}
	watcher, err := db.GetByDomain(domain).One()
	if err != nil {
		watcher, err = db.New(domain, post.Interval)
		if err != nil {
			util.Error(err, w)
			return
		}
	}
	watcher.SetLowerInterval(post.Interval)
	user, err := auth.GetUser(r)
	if err != nil {
		util.Error(err, w)
		return
	}
	watcher.AddUser(*user)
	err = watcher.Save()
	log.Info("%+v", watcher)
	dispatcher.AddDomain(domain)
	util.ToJSON(watcher, err, w)
}
Example #16
0
/*
	Search is used for retrieving notifications. It accepts the following
	GET params:


*/
func Search(w http.ResponseWriter, r *http.Request, params url.Values, limit, offset int) {
	query := db.SELECT
	var where []string
	var args []interface{}
	var orderBy = ""
	i := 1
	// inject user
	user, err := auth.GetUser(r)
	if err != nil {
		util.Error(err, w)
		return
	}
	where = append(where, fmt.Sprintf("user_id = $%d", i))
	args = append(args, user.ID)
	i++
	for k, _ := range params {
		switch k {
		case "duuid":
			where = append(where, fmt.Sprintf("domain = $%d", i))
			args = append(args, params.Get(k))
			i++
		case "orderBy":
			orderBy = fmt.Sprintf("ORDER BY $%d ", i)
			args = append(args, params.Get(k))
			if v, ok := params["order"]; ok {
				order := strings.ToLower(v[0])
				if order == "desc" {
					orderBy += "DESC "
				} else if order == "asc" {
					orderBy += "ASC "
				}
			}
		}
	}
	if len(where) > 0 {
		query += "WHERE " + strings.Join(where, " AND ") + " "
	}
	if len(orderBy) > 0 {
		query += orderBy + " "
	}
	query += fmt.Sprintf("LIMIT $%d OFFSET $%d", len(args)+1, len(args)+2)
	args = append(args, limit, offset)
	log.Info("Query: " + query)
	log.Info("Args: %+v", args)
	notificationList, err := db.GetList(query, args...)
	util.ToJSON(notificationList, err, w)
}
Example #17
0
func New(db *bolt.DB) httpHandler {
	config := jconfig.LoadConfig("config.json")
	key := config.GetString("session_secret")
	var err error
	str, err = store.New(db, store.Config{}, []byte(key))
	if err != nil {
		panic(err)
	}
	sessionName = config.GetString("session_name")
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				session, err := GetSession(r)
				if err != nil {
					util.Error(err, w)
					return
				}
				if t, ok := session.Values["expires"]; ok {
					if time.Now().Before(t.(time.Time)) {
						// authed
						if u, ok := session.Values["user"]; ok {
							w.Header().Set("X-User", u.(string))
						}
						w.Header().Set("X-Expires", t.(time.Time).String())
						h.ServeHTTP(w, r)
						return
					}
				}
				user, pass, ok := r.BasicAuth()
				if ok {
					if checkUserIn(user, pass, w, r) {
						h.ServeHTTP(w, r)
						return
					}
				}
				if r.URL.Path == "/api/v1/auth/" {
					h.ServeHTTP(w, r)
					return
				}
				w.WriteHeader(http.StatusUnauthorized)
			},
		)
	}
}
Example #18
0
/*
	Search is used for retrieving whois records for a domain. It accepts the following
	GET params:

	+ uuid		- uuid of record
	+ duuid 	- uuid of domain
	+ domain	- string of domain

*/
func Search(w http.ResponseWriter, r *http.Request, params url.Values, limit, offset int) {
	query := db.SELECT
	var domain domains.Domain
	var where []string
	var args []interface{}
	var orderBy string
	i := 1
	for k, _ := range params {
		switch k {
		case "orderBy":
			orderBy = fmt.Sprintf("ORDER BY %s ", params.Get(k))
			if v, ok := params["order"]; ok {
				order := strings.ToLower(v[0])
				if order == "desc" {
					orderBy += "DESC "
				} else if order == "asc" {
					orderBy += "ASC "
				}
			}
		case "uuid":
			where = append(where, fmt.Sprintf(k+" = $%d", i))
			args = append(args, params.Get(k))
			i++
		case "duuid", "domain":
			where = append(where, fmt.Sprintf("domain = $%d", i))
			args = append(args, params.Get(k))
			v := params.Get(k)
			params.Del("duuid")
			params.Del("domain")
			params.Set("domain", v)
			i++
		case "name":
			name, tld, err := tlds.DetectDomainAndTLD(params.Get(k))
			if err != nil {
				util.Error(err, w)
				return
			}
			domain, err = domains.GetByNameAndTLD(name, tld).One()
			if err != nil {
				domain = domains.New(name, tld)
				err = domain.Insert()
				if err != nil {
					util.Error(err, w)
					return
				}
			}
			where = append(where, fmt.Sprintf("domain = $%d", i))
			args = append(args, domain.UUID.String())
			i++
		case "email":
			where = append(where, fmt.Sprintf("emails ? $%d", i))
			args = append(args, params.Get(k))
			i++
		case "raw":
			where = append(where, fmt.Sprintf("raw_whois ->>0 ILIKE $%d", i))
			args = append(args, "%"+params.Get(k)+"%")
			i++
		}
	}
	if len(where) > 0 {
		query += "WHERE " + strings.Join(where, " AND ") + " "
	}
	if len(orderBy) > 0 {
		query += orderBy + " "
	}
	query += fmt.Sprintf("ORDER BY added DESC LIMIT $%d OFFSET $%d", len(args)+1, len(args)+2)
	args = append(args, limit, offset)
	log.Info("Query: " + query)
	log.Info("Args: %+v", args)
	recordList, err := db.GetList(query, args...)
	if err != nil {
		panic(err)
	}
	// check for non sql errors
	// if we have no results dispatch a worker to get one
	if len(recordList) == 0 {
		if len(domain.Name) == 0 {
			// no domain lets grab one using what we assume is a duuid
			if duuid := params.Get("domain"); duuid != "" {
				log.Info("duuid: " + duuid)
				domain, err = domains.GetByUUID(duuid).One()
				if err != nil {
					util.Error(err, w)
					return
				}
			}
		}
		if len(domain.Name) == 0 {
			log.Error("Unable to detect domain for whois lookup, params: %+v", params)
			util.Error(errors.New("Unable to find domain for whois lookup."), w)
			return
		}
		result := <-dispatcher.AddDomain(domain)
		recordList = append(recordList, result)
	}
	util.ToJSON(recordList, err, w)
}
Example #19
0
File: auth.go Project: jawr/wall
func Auth(w http.ResponseWriter, r *http.Request) {
	var params = r.URL.Query()
	var code = params.Get("code")
	if len(code) == 0 {
		utils.Error(errors.New("No code supplied for auth."), w)
		return
	}

	cfg := config.Get()
	clientID := cfg.GetString("google_client_id")
	clientSecret := cfg.GetString("google_client_secret")
	conf := &oauth2.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RedirectURL:  "postmessage",
		Scopes: []string{
			"https://www.googleapis.com/auth/plus.login",
			"https://www.googleapis.com/auth/plus.profile.emails.read",
		},
		Endpoint: google.Endpoint,
	}

	tok, err := conf.Exchange(oauth2.NoContext, code)
	if err != nil {
		utils.Error(errors.New("Unable to exchange code for a token."), w)
		return
	}

	if !tok.Valid() {
		// 401
		utils.Error(errors.New("Invalid token."), w)
		return
	}

	client := conf.Client(oauth2.NoContext, tok)
	service, err := plus.New(client)
	if err != nil {
		utils.Error(errors.New("Unable to create a transport client."), w)
		return
	}

	gplusID, err := decodeIDToken(tok.Extra("id_token").(string))
	if err != nil {
		utils.Error(errors.New("Unable to decode ID Token."), w)
		return
	}

	people := service.People.Get(gplusID)
	person, err := people.Do()
	if err != nil {
		log.Println(err)
		utils.Error(errors.New("Unable to get Google Plus profile"), w)
		return
	}

	user, err := users.GetByID(person.Id)
	if err != nil {
		user, err = users.New(person.DisplayName, person.Id)
		if err != nil {
			log.Println(err)
			utils.Error(errors.New("Unable to create new user in the database"), w)
			return
		}
	}

	log.Printf("Person: %+v\n", person)
	// logged in
	session, err := GetSession(r)
	if err != nil {
		log.Println(err)
		utils.Error(errors.New("Unable to get session."), w)
		return
	}
	session.Values["expires"] = time.Now().Add(time.Hour * 24)
	session.Values["user"] = user
	session.Options.MaxAge = 86400 * 30

	if err := str.Save(r, w, session); err != nil {
		log.Println(err)
		utils.Error(errors.New("Unable to save session."), w)
		return
	}

	utils.ToJSON(user, err, w)
}