示例#1
0
func LoginPost(lu forms.Login, session sessions.Session, r render.Render, dbh *db.Dbh) {
	errs := ValidateLogin(&lu)
	if len(errs) > 0 {
		log.Printf("errors: %+v\n", errs)
	}

	user := dbh.GetUserByEmail(lu.Email)

	match := auth.MatchPassword(lu.Password, user.Password, user.Salt)

	if match {
		sessionkey := SessionKey(user.Email, user.Password, user.Salt)

		session.Set("loggedin", "true")
		session.Set("uid", user.Id)
		session.Set("email", user.Email)
		session.Set("key", sessionkey)

		dbh.CreateSession(models.UserSession{UserId: user.Id, SessionKey: sessionkey, Active: true, Timestamp: time.Now().Unix()})

		r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "albums"}, "/"), http.StatusFound)
		return
	}

	session.Set("flash", "Invalid Email or Password")

	r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "login"}, "/"), http.StatusFound)
}
示例#2
0
func Verify(res http.ResponseWriter, req *http.Request, r render.Render, dbh *db.Dbh) {
	pk := req.FormValue("user_private_key")
	a := req.FormValue("file_album")

	album := dbh.GetAlbum(a)

	if album.Id > 0 && album.Privatekey == pk {
		return
	}

	if pk == "" || pk != utils.ImageCfg.SecretKey() {
		log.Printf("Upload failed: Invalid Private Key (%s)\n", pk)
		r.JSON(http.StatusUnauthorized, Response{"error": http.StatusUnauthorized, "code": "Invalid Private Key", "name": a})
		return
	}

	if a == "" {
		log.Printf("Upload failed: Invalid Album Name (%s)\n", a)
		r.JSON(http.StatusUnauthorized, Response{"error": http.StatusUnauthorized, "code": "Invalid Album Name", "name": a})
		return
	}

	log.Println("verify: good")
	return
}
示例#3
0
func Tags(su models.User, dbh *db.Dbh, p *models.Page, r render.Render) {
	tags := dbh.GetAllTags()

	p.SetUser(su)
	p.SetTitle("Tags")
	p.Data = tags
	p.Encoding = "json"

	encoder.Render(p.Encoding, 200, "tags", p, r)
}
示例#4
0
func TagImage(res http.ResponseWriter, req *http.Request, dbh *db.Dbh) {
	tag := req.FormValue("tag")
	image := req.FormValue("image")

	imagetag := dbh.TagImage(tag, image)
	log.Println(imagetag)

	http.Redirect(res, req, strings.Join([]string{utils.AppCfg.Url(), "image", image}, "/"), http.StatusFound)
	return
}
示例#5
0
func Logout(session sessions.Session, r render.Render, dbh *db.Dbh) {
	sessionkey := session.Get("key")
	uid := session.Get("uid")

	session.Set("loggedin", "false")
	session.Set("uid", nil)
	session.Set("email", nil)
	session.Set("key", nil)

	if uid != "" && uid != nil {
		dbh.DestroySession(uid.(int64), sessionkey.(string))
	}
	r.Redirect(utils.AppCfg.Url(), http.StatusFound)
}
示例#6
0
func AlbumUpdate(req *http.Request, r render.Render, su models.User, dbh *db.Dbh, p *models.Page) {
	p.SetUser(su)

	var reader io.Reader = req.Body
	b, e := ioutil.ReadAll(reader)
	if e != nil {
		log.Println(e)
	}

	var f interface{}
	err := json.Unmarshal(b, &f)
	if err != nil {
		log.Println(err)
	}

	m := f.(map[string]interface{})
	md := m["data"].(map[string]interface{})

	// Default status
	var status string = "Permission Denied"
	var code int = 401

	mi := int64(md["Id"].(float64))
	mo := int64(md["Owner"].(float64))
	name := md["Name"].(string)

	album := dbh.GetAlbumById(mi)

	if album.Id == mi && album.User == mo && su.Id == mo {
		mAlbum := models.Album{
			Id:          mi,
			Description: md["Description"].(string),
			Name:        md["Name"].(string),
			User:        mo,
			Poster:      md["Poster"].(string),
			Private:     md["Private"].(bool),
			Privatekey:  md["Privatekey"].(string)}

		log.Printf("mAlbum: %+v\n", mAlbum)
		uAlbum := dbh.AlbumUpdate(mAlbum)
		log.Printf("uAlbum: %+v\n", uAlbum)
		status = "Success"
		code = 200
	}

	log.Println("Album Update: ", "Name: ", name, " Album Id: ", album.Id, "=", mi, " Album User: "******"=", mo, " Session: ", su.Id, "=", mo, " Status: ", status)

	p.Data = models.AlbumResult{Status: status}
	encoder.Render("json", code, "", p, r)
}
示例#7
0
func AlbumPrivate(args martini.Params, session sessions.Session, su models.User, r render.Render, res http.ResponseWriter, req *http.Request, dbh *db.Dbh) {
	name := args["name"]
	state, err := strconv.ParseBool(args["state"])
	if err != nil {
		log.Println("Invalid state: ", args["state"])
		return
	}
	log.Printf("uid: %d name: %s state: %t\n", su.Id, name, state)

	if su.Id > 0 {
		dbh.SetAlbumPrivacy(su.Id, name, state)
	}

	http.Redirect(res, req, strings.Join([]string{utils.AppCfg.Url(), "albums"}, "/"), http.StatusFound)
	return
}
示例#8
0
func AlbumCreate(req *http.Request, r render.Render, su models.User, dbh *db.Dbh, p *models.Page) {
	// Default status
	var status string = "Permission Denied"
	var code int = 401

	var reader io.Reader = req.Body
	b, e := ioutil.ReadAll(reader)
	if e != nil {
		log.Println(e)
	}

	adata := string(b)

	params := strings.Split(adata, "&")

	var name, privatekey, description string
	for _, val := range params {
		vars := strings.Split(val, "=")
		k := strings.ToLower(vars[0])
		v := vars[1]
		switch k {
		case "name":
			name = v
		case "privatekey":
			privatekey = v
		case "description":
			description = v
		}

	}
	if len(description) == 0 {
		const layout = "Auto-created 2 January 2006"
		t := time.Now()
		description = t.Format(layout)
	}

	// Add album
	nAlbum := models.Album{Name: name, User: su.Id, Privatekey: privatekey, Private: true, Description: description, Timestamp: time.Now().Unix()}
	album := dbh.AddAlbum(nAlbum)
	if album.Id > 0 {
		code = 200
		status = "Success"
	}

	p.Data = models.AlbumResult{Status: status}
	encoder.Render("json", code, "", p, r)
}
示例#9
0
func ImagePage(args martini.Params, su models.User, res http.ResponseWriter, req *http.Request, r render.Render, dbh *db.Dbh, p *models.Page) {
	name := args["name"]

	image := dbh.FirstImageByName(name)
	tags := dbh.GetAllTagsByImageId(image.Id)

	errs := make(map[string]string)
	form := utils.GenerateForm(&forms.Tag{Image: name}, "/tag", "POST", errs)

	p.SetUser(su)
	p.SetTitle("Image")

	src := fmt.Sprintf("%s/i/%s", utils.AppCfg.Url(), name)
	fullsrc := fmt.Sprintf("%s/o/%s", utils.AppCfg.Url(), name)
	p.Data = ImagePageVars{Name: src, Full: fullsrc, Tags: tags, Form: form}

	encoder.Render(p.Encoding, 200, "image", p, r)
}
示例#10
0
func genUserName(email string, dbh *db.Dbh) string {
	name := strings.Split(email, "@")[0]

	var u models.User
	u = dbh.GetUserByUserName(name)
	if u.Id != 0 {
		var i = 0
		var tmp_name string
		for {
			i++
			tmp_name = strings.Join([]string{name, strconv.Itoa(i)}, "")
			u = dbh.GetUserByUserName(tmp_name)
			if u.Id == 0 {
				return tmp_name
			}
		}
	}
	return name
}
示例#11
0
func getSessionUser(session sessions.Session, dbh *db.Dbh) (user models.User) {
	var email, sessionkey, loggedin string
	var suid int64

	sloggedin := session.Get("loggedin")
	if sloggedin != nil {
		loggedin = sloggedin.(string)
	}

	semail := session.Get("email")
	if semail != nil {
		email = semail.(string)
	}

	ssessionkey := session.Get("key")
	if ssessionkey != nil {
		sessionkey = ssessionkey.(string)
	}

	ssuid := session.Get("uid")
	if ssuid != nil {
		suid = ssuid.(int64)
	}

	if loggedin != "true" || sessionkey == "" {
		return
	}

	usk := dbh.GetUserByIdSessionKey(suid, sessionkey)
	if usk.Active != true || usk.Id < 1 {
		return
	}

	u := dbh.GetUserById(suid)
	if u.Email != email {
		return
	}

	return u
}
示例#12
0
func ImageTrash(args martini.Params, su models.User, dbh *db.Dbh, r render.Render, p *models.Page) {
	album := args["album"]
	name := args["name"]

	// Default status
	var status string = "Permission Denied"
	var code int = 401

	log.Printf("Trashing image: %s from %s", name, album)

	image := dbh.FirstImageByName(name)
	if su.Id == image.User {
		image.Trashed = true
		dbh.UpdateImage(image)
		status = "Success"
		code = 200
	}

	p.SetUser(su)
	p.Data = TrashRecover{Name: name, Album: album, Action: "Trash", Status: status}

	encoder.Render("json", code, "", p, r)
}
示例#13
0
func Tagged(args martini.Params, r render.Render, su models.User, dbh *db.Dbh, p *models.Page) {

	tag := args["tag"]

	images := dbh.GetImagesWithTag(tag)

	var imageLinks []imageLink
	for _, f := range images {
		if f.Trashed {
			log.Println("Trashed: ", f)
			continue
		}
		imageLinks = append(imageLinks, imageLink{Title: f.Name, FileName: f.Name})
	}

	p.SetUser(su)
	p.SetTitle("Tagged", tag)
	description := fmt.Sprintf("Images tagged as %s", tag)
	p.Data = TaggedVars{Title: tag, Description: description, ImageLinks: imageLinks}
	p.Encoding = "json"

	encoder.Render(p.Encoding, 200, "image_link", p, r)
}
示例#14
0
func Album(args martini.Params, su models.User, session sessions.Session, r render.Render, dbh *db.Dbh, p *models.Page) {
	name := args["name"]
	auser := args["user"]
	key := args["key"]

	if auser != "" {
		log.Println("album user: "******"flash", "Login Required")
		r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "login"}, "/"), http.StatusFound)
		return
	}

	images := dbh.GetAllImagesByAlbumId(album.Id)

	var imageLinks []imageLink
	for _, f := range images {
		if f.Trashed {
			continue
		}
		var file_name = f.Name
		if f.HashId != "" {
			file_name = f.HashId
		}
		log.Println(file_name, f)
		imageLinks = append(imageLinks, imageLink{Id: f.Id, Title: f.Name, FileName: file_name, Owner: f.User})
	}

	p.SetTitle("Album", name)
	p.SetUser(su)
	p.Data = AlbumVars{Title: name, Description: album.Description, ImageLinks: imageLinks}

	encoder.Render(p.Encoding, 200, "image_link", p, r)
}
示例#15
0
func SetupAdminPost(sa forms.SetupAdmin, args martini.Params, session sessions.Session, r render.Render, res http.ResponseWriter, dbh *db.Dbh) {
	errs := Validate(&sa)
	if len(errs) > 0 {
		fmt.Printf("%+v\n", errs)
	}

	v := session.Get("setup")
	if v != "true" {
		http.Error(res, "Unauthorized", http.StatusUnauthorized)
		return
	}

	user := dbh.GetUserByEmail(sa.Email)

	if user.Id > 0 {
		fmt.Println("user already exists")
		session.Set("uid", user.Id)
	}

	if user.Id == 0 {
		fmt.Println("id: 0")
		hash, salt, err := auth.EncryptPassword(sa.Password)
		if err != nil {
			fmt.Println("hash err: ", err)
		}
		newuser := models.User{Name: sa.Name, Email: sa.Email, Password: hash, Salt: salt, Timestamp: time.Now().Unix()}
		dbh.InsertUser(newuser)
		session.Set("uid", newuser.Id)
	}

	uid := session.Get("uid")

	fmt.Println("uid: ", uid)
	genform := utils.GenerateForm(&sa, "/setup", "POST", errs)
	r.HTML(200, "setup", genform)
}
示例#16
0
func QR(args martini.Params, su models.User, dbh *db.Dbh, session sessions.Session, r render.Render, res http.ResponseWriter, req *http.Request) {
	name := args["name"]

	album := dbh.GetAlbum(name)

	key := album.Privatekey
	private := album.Private

	if private && su.Id != album.User || album.Id == 0 {
		session.Set("flash", "Login Required")
		r.Redirect(strings.Join([]string{utils.AppCfg.Url(), "login"}, "/"), http.StatusFound)
		return
	}

	log.Printf("name: %s key: %s private: %t\n", name, key, private)

	file := createQR(name, key)

	dir := http.Dir(utils.ImageCfg.QR())
	f, err := dir.Open(file)
	if err != nil {
		// discard the error?
		return
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		return
	}

	res.Header().Set("X-Content-Type-Options", "nosniff")
	res.Header().Set("Expires", utils.ExpiresHeader())
	res.Header().Add("Content-Type", "image/png")
	http.ServeContent(res, req, file, fi.ModTime(), f)
}
示例#17
0
func AlbumDelete(args martini.Params, req *http.Request, r render.Render, su models.User, dbh *db.Dbh, p *models.Page) {
	// Default status
	var result string = "Not Deleted"
	var status string = "Permission Denied"
	var code int = 401

	name := args["name"]

	album := dbh.GetAlbumByName(name)
	if album.User == su.Id {
		status = "Success"
		result = "Deleted"
		dAlbum := dbh.AlbumDelete(album)
		log.Printf("%+v", dAlbum)
	}
	if album.Id == 0 {
		status = "Album not found"
		code = 404
	}

	p.Data = models.AlbumResult{Name: name, Result: result, Status: status}
	log.Println("Album Delete: User: "******" Album: ", name, " Result: ", result, " Status: ", status)
	encoder.Render("json", code, "", p, r)
}
示例#18
0
func ListDB(args martini.Params, su models.User, r render.Render, p *models.Page, dbh *db.Dbh) {

	images := dbh.GetAllImages()

	var album models.Album
	for _, image := range images {
		album = dbh.GetAlbum(image.Album)
		image.AlbumId = album.Id
		nImage := dbh.UpdateImage(image)
		log.Println(nImage)
	}

	return
}
示例#19
0
func AlbumMove(req *http.Request, r render.Render, su models.User, dbh *db.Dbh, p *models.Page) {
	// Default status
	var status string = "Permission Denied"
	var code int = 401

	var reader io.Reader = req.Body
	b, e := ioutil.ReadAll(reader)
	if e != nil {
		log.Println(e)
	}

	var f Data
	err := json.Unmarshal(b, &f)
	if err != nil {
		log.Println(err)
	}
	log.Println(f)

	albumId := f.Md.AlbumId
	album := dbh.GetAlbumById(albumId)
	log.Println("album: ", albumId)

	if album.User == su.Id {
		status = "Success"
		code = 200

		var image models.Image
		for _, f := range f.Md.Images {
			imageId, err := strconv.ParseInt(f.Id, 10, 10)
			if err != nil {
				log.Println("invalid image id: ", f.Id)
			}
			log.Println("Moving: ", f.Name, imageId)

			image = dbh.GetImageById(imageId)
			if image.User != su.Id {
				status = "Permission Denied"
				code = 401
				continue
			}
			fromId := image.AlbumId
			image.AlbumId = albumId
			_ = dbh.UpdateImage(image)
			log.Printf("Moved %s from: %d to: %d status: %s code: %d\n", f.Name, fromId, albumId, status, code)
		}

	}
	p.Data = status
	encoder.Render("json", code, "", p, r)
}
示例#20
0
func UploadImage(w http.ResponseWriter, upload models.ImageUpload, req *http.Request, r render.Render, dbh *db.Dbh) {
	ur := &models.UploadResult{}

	rEmail := upload.Email
	rAlbum := upload.Album
	rPrivateKey := upload.PrivateKey

	fiName := upload.File.Filename

	upload_time := time.Now().Unix()

	ur.SetCode(200)
	ur.SetResult("success")
	ur.SetName(fiName)

	tmp_file := utils.ImageCfg.Root() + ur.GetName()

	if Exists(tmp_file) {
		log.Println("Error: File exists. (" + tmp_file + ")")
		ur.SetCode(2)
		ur.SetResult("File exists")
		r.JSON(500, ur)
		return
	}

	out, err := os.Create(tmp_file)
	if err != nil {
		log.Println("Error: Unable to open file.")
		ur.SetCode(500)
		ur.SetResult("Failed to open the file for writing.")
		r.JSON(500, ur)
		return
	}
	defer out.Close()

	fi, err := upload.File.Open()
	if err != nil {
		log.Println("fi err: ", err)
		ur.SetCode(500)
		ur.SetResult(err.Error())
		r.JSON(500, ur)
		return
	}
	defer fi.Close()

	_, err = io.Copy(out, fi)
	if err != nil {
		log.Println("Error: Failed to copy file.")
		ur.SetCode(500)
		ur.SetResult("Failed to copy file to new location.")
		r.JSON(500, ur)
		return
	}

	log.Printf("tmp_file: %s\n", tmp_file)

	// Add image uploader to database
	dbh.AddUploader(models.Uploader{Email: rEmail, Timestamp: upload_time})

	// Setup hashid to create unique file name
	var hid models.HashID
	hid.Init(utils.AppCfg.SecretKey(), 10)

	// Get user id
	user := dbh.GetUserByEmail(rEmail)
	log.Println("user: "******"uploader user: "******"album: ", album)

	nAlbum := dbh.GetAlbum(rAlbum)

	// Add image
	image := dbh.AddImage(models.Image{
		Name:      fiName,
		Album:     rAlbum,
		User:      user.Id,
		AlbumId:   nAlbum.Id,
		Timestamp: upload_time})

	// Add image id to hashid - seg 3
	hid.AddId(int(image.Id))

	// Add upload time to hashid - seg 4
	hid.AddId(int(upload_time))

	// Get file extension and create new file name
	extension := filepath.Ext(fiName)
	nname := hid.Encrypt() + extension
	log.Printf("New name: %s\n", nname)

	image.HashId = nname
	dbh.UpdateImage(image)

	// Rename file to new name
	hash_name := utils.ImageCfg.Root() + nname
	os.Rename(tmp_file, hash_name)

	ur.SetName(utils.AppCfg.Url() + "/image/" + nname)

	// Create Thumb
	tname := utils.ImageCfg.Thumbs() + nname

	if !Exists(string(tname)) {
		okc := make(chan bool, 1)
		utils.CreateThumb(okc, hash_name, tname, 150, 150)
		<-okc
	}

	log.Printf("%# v\n", pretty.Formatter(album))
	log.Printf("%# v\n", image)
	log.Printf("%# v\n", pretty.Formatter(ur))

	r.JSON(200, ur)
}
示例#21
0
func Uploader(r render.Render, dbh *db.Dbh) {
	upper := dbh.GetAllUploaders()
	log.Println(upper)

	r.JSON(200, upper)
}