func writeFileResponse(filename string, bytes []byte, w http.ResponseWriter, r *http.Request) *model.AppError { w.Header().Set("Cache-Control", "max-age=2592000, public") w.Header().Set("Content-Length", strconv.Itoa(len(bytes))) w.Header().Del("Content-Type") // Content-Type will be set automatically by the http writer // attach extra headers to trigger a download on IE, Edge, and Safari ua := user_agent.New(r.UserAgent()) bname, _ := ua.Browser() parts := strings.Split(filename, "/") filePart := strings.Split(parts[len(parts)-1], "?")[0] w.Header().Set("Content-Disposition", "attachment;filename=\""+filePart+"\"") if bname == "Edge" || bname == "Internet Explorer" || bname == "Safari" { w.Header().Set("Content-Type", "application/octet-stream") } // prevent file links from being embedded in iframes w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("Content-Security-Policy", "Frame-ancestors 'none'") w.Write(bytes) return nil }
func (h *HttpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { url, err := h.getFileUrl(r) if err != nil { rw.WriteHeader(http.StatusBadRequest) return } redirect := func() { http.Redirect(rw, r, url.String(), http.StatusTemporaryRedirect) } ua := user_agent.New(r.UserAgent()) name, version := ua.Browser() if name != "Chrome" || strings.Index(version, "52.") != 0 { redirect() return } d, err := h.DimensionsCache.Get(url) if err != nil { rw.WriteHeader(http.StatusInternalServerError) return } if d.SwapHeightAndWidth == 0 { redirect() return } h.Proxy.ServeHTTP(rw, r) }
func (uap *UADetectionPlugin) Log(req *http.Request, res *http.Response, ctx *apiplexy.APIContext) error { ua := user_agent.New(req.UserAgent()) ctx.Log["ua_mobile"] = ua.Mobile() ctx.Log["ua_bot"] = ua.Bot() browser, version := ua.Browser() ctx.Log["ua_browser"] = browser ctx.Log["ua_version"] = version ctx.Log["ua_os"] = ua.OS() return nil }
func insertStatistic(r *http.Request) { // 后台访问暂不计入统计中 if strings.Contains(r.RequestURI, "/admin") { return } db := openDatabase() if db == nil { return } defer closeDatabase(db) //db.execInsert("statistic", "null,?,?,?,?,?,?,?,?,?,?,?", ) tx, err := db.Begin() if err != nil { return } stmt, err := tx.Prepare("insert into statistic values(null,?,?,?,?,?,?,?,?,?,?,?)") if err != nil { fmt.Println(err) return } ua := user_agent.New(r.UserAgent()) /* id, url, referer, refererhost, refererpath, useragent, time, platform, os, browser, browserver ip, */ refererpath := "" refererhost := "" referer, err := url.Parse(r.Referer()) if err == nil { refererhost = referer.Host refererpath = referer.Path } browsername, browserversion := ua.Browser() if _, err = stmt.Exec( r.RequestURI, // url r.Referer(), // referer refererhost, // refererhost refererpath, // refererpath ua.UA(), // useragent time.Now().Unix(), // time ua.Platform(), // platform ua.OS(), // os browsername, // browser browserversion, // browserver getIpAddrByStr(r.RemoteAddr)); err != nil { fmt.Println(err) return } defer stmt.Close() tx.Commit() return }
func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("downloadComplianceReport") { return } if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed || !*utils.License.Features.Compliance || einterfaces.GetComplianceInterface() == nil { c.Err = model.NewLocAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "") return } params := mux.Vars(r) id := params["id"] if len(id) != 26 { c.SetInvalidParam("downloadComplianceReport", "id") return } if result := <-Srv.Store.Compliance().Get(id); result.Err != nil { c.Err = result.Err return } else { job := result.Data.(*model.Compliance) c.LogAudit("downloaded " + job.Desc) if f, err := ioutil.ReadFile(*utils.Cfg.ComplianceSettings.Directory + "compliance/" + job.JobName() + ".zip"); err != nil { c.Err = model.NewLocAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error()) return } else { w.Header().Set("Cache-Control", "max-age=2592000, public") w.Header().Set("Content-Length", strconv.Itoa(len(f))) w.Header().Del("Content-Type") // Content-Type will be set automatically by the http writer // attach extra headers to trigger a download on IE, Edge, and Safari ua := user_agent.New(r.UserAgent()) bname, _ := ua.Browser() w.Header().Set("Content-Disposition", "attachment;filename=\""+job.JobName()+".zip\"") if bname == "Edge" || bname == "Internet Explorer" || bname == "Safari" { // trim off anything before the final / so we just get the file's name w.Header().Set("Content-Type", "application/octet-stream") } w.Write(f) } } }
func (this *PostController) BySlug() { post_slug := this.Ctx.Input.Param(":slug") post_model := models.NewPostModel() post, err := post_model.BySlug(post_slug) if err != nil { this.Abort("404") } this.setPost(post) ua := user_agent.New(this.Ctx.Request.UserAgent()) if ua.Bot() { post_model.ViewedBy(post.PostId, "bot") } else { post_model.ViewedBy(post.PostId, "human") } }
func CheckBrowserCompatability(c *api.Context, r *http.Request) bool { ua := user_agent.New(r.UserAgent()) bname, bversion := ua.Browser() browsers := strings.Split(browsersNotSupported, ";") for _, browser := range browsers { version := strings.Split(browser, "/") if strings.HasPrefix(bname, version[0]) && strings.HasPrefix(bversion, version[1]) { return false } } return true }
func CheckBrowserCompatability(c *api.Context, r *http.Request) bool { ua := user_agent.New(r.UserAgent()) bname, bversion := ua.Browser() browsers := strings.Split(browsersNotSupported, ";") for _, browser := range browsers { version := strings.Split(browser, "/") if strings.HasPrefix(bname, version[0]) && strings.HasPrefix(bversion, version[1]) { c.Err = model.NewAppError("CheckBrowserCompatability", "Your current browser is not supported, please upgrade to one of the following browsers: Google Chrome 21 or higher, Internet Explorer 10 or higher, FireFox 14 or higher", "") return false } } return true }
func CheckBrowserCompatability(c *api.Context, r *http.Request) bool { ua := user_agent.New(r.UserAgent()) bname, bversion := ua.Browser() browsers := strings.Split(browsersNotSupported, ";") for _, browser := range browsers { version := strings.Split(browser, "/") if strings.HasPrefix(bname, version[0]) && strings.HasPrefix(bversion, version[1]) { c.Err = model.NewLocAppError("CheckBrowserCompatability", "web.check_browser_compatibility.app_error", nil, "") return false } } return true }
func (uae UserAgentExtractor) Handle(c *mv.Context) { ua := user_agent.New(c.Request.Header["User-Agent"][0]) name, version := ua.Browser() browserEngine, browserEngineVersion := ua.Engine() browserInfo := BrowserInfo{ verbose: uae.verbose, Name: name, Version: version, OS: ua.OS(), Engine: browserEngine, EngineVersion: browserEngineVersion, Localization: ua.Localization(), Platform: ua.Platform(), Mobile: ua.Mobile(), } c.WithValue(browserInfoKey, browserInfo) c.Next() }
func testClient(client *userAgent) (success bool) { var crawler bool switch client.Type { case "crawlers", "browsers": crawler = client.Type == "crawlers" break default: return } for _, uastr := range client.UserAgents { ua := user_agent.New(uastr) if crawler && !ua.Bot() { glog.Warningf("%s not recognized %q", client.Type, uastr) } else if !crawler && ua.Bot() { glog.Warningf("%s recognized as bot %q", client.Type, uastr) } else { return true } } return }
func (self *Server) saveShow(t time.Time, sesUuid string, storeID int, params string, remoteIp string, acceptLanguage string, refererSrc string, userAgent string) { var zoneId pgx.NullInt32 var uaBrowserVersion pgx.NullInt16 var uaBrowserFamily pgx.NullString var zoneName pgx.NullString var referer pgx.NullString if err := self.DB.QueryRow("getZoneById", storeID).Scan(&zoneId, &zoneName); err != nil { self.Log.Error("Is not", "zoneId", storeID) } ua := user_agent.New(userAgent) browserFamily, version := ua.Browser() // fmt.Println("------------ userAgent ------------") // fmt.Printf("%v", userAgent) if len(version) > 2 { // fmt.Println("------------ version ----------") // fmt.Printf("%v", version) browserVersion, err := strconv.Atoi(version[0:strings.Index(version, ".")]) if err == nil { uaBrowserVersion = pgx.NullInt16{Int16: int16(browserVersion), Valid: true} } } if len(browserFamily) > 2 { uaBrowserFamily = pgx.NullString{String: browserFamily, Valid: true} } ip, ipv4, mac := adscore.ParseParams(params) if len(refererSrc) > 1 { referer = pgx.NullString{String: refererSrc, Valid: true} } if _, err := self.DB.Exec("setShowBanner", t, sesUuid, zoneId, ua.Bot(), mac, ip, ipv4, acceptLanguage, uaBrowserFamily, uaBrowserVersion, ua.OS(), ua.Platform(), ua.Mobile(), userAgent, referer); err != nil { self.Log.Error("Exec", "setShowBanner", err) } }
func (event *SnowplowEvent) Transform(request []byte, geo *geoip.GeoIP) error { event.Body = request normString, err := strconv.Unquote(`"` + string(request) + `"`) if err != nil { return err } normString = strings.Replace(normString, "\" ", "", -1) snowplowRequest := &SnowplowRequest{} err = json.Unmarshal([]byte(normString), snowplowRequest) if err != nil { return err } // Binding first level nginx fields checkStringForNull(snowplowRequest.IPAddress, &event.UserIP) event.CollectorTstamp = time.Now() // checkStringForNull(snowplowRequest.Referer, &event.PageReferrer) checkStringForNull(snowplowRequest.Useragent, &event.Useragent) // Binding snowplow data snowplowData := snowplowRequest.RequestBody.Data[0] // Bind string values checkStringForNull(snowplowData.Event, &event.Event) checkStringForNull(snowplowData.PageURL, &event.PageURL) checkStringForNull(snowplowData.PageTtile, &event.PageTtile) checkStringForNull(snowplowData.PageReferrer, &event.PageReferrer) checkStringForNull(snowplowData.VTracker, &event.VTracker) checkStringForNull(snowplowData.Aid, &event.Aid) checkStringForNull(snowplowData.Platform, &event.Platform) checkStringForNull(snowplowData.OsTimezone, &event.OsTimezone) checkStringForNull(snowplowData.BrLang, &event.BrLang) checkStringForNull(snowplowData.DocCharset, &event.DocCharset) checkStringForNull(snowplowData.EventID, &event.EventID) checkStringForNull(snowplowData.DomainUserID, &event.DomainUserID) checkStringForNull(snowplowData.UserFingerprint, &event.UserFingerprint) checkStringForNull(snowplowData.SeCategory, &event.SeCategory) checkStringForNull(snowplowData.SeAction, &event.SeAction) checkStringForNull(snowplowData.SeLabel, &event.SeLabel) checkStringForNull(snowplowData.SeProperty, &event.SeProperty) checkFloatForNull(snowplowData.SeValue, &event.SeValue) // Bind integer values checkIntForNull(snowplowData.BrColorDepth, &event.BrColorDepth) checkIntForNull(snowplowData.VisitNum, &event.VisitNum) checkIntForNull(snowplowData.UserID, &event.UserID) // Bind boolean values event.BrPDF, _ = strconv.ParseBool(snowplowData.BrPDF) event.BrQT, _ = strconv.ParseBool(snowplowData.BrQT) event.BrRealPlayer, _ = strconv.ParseBool(snowplowData.BrRealPlayer) event.BrWMA, _ = strconv.ParseBool(snowplowData.BrWMA) event.BrDir, _ = strconv.ParseBool(snowplowData.BrDir) event.BrFlash, _ = strconv.ParseBool(snowplowData.BrFlash) event.BrJava, _ = strconv.ParseBool(snowplowData.BrJava) event.BrGears, _ = strconv.ParseBool(snowplowData.BrGears) event.BrAg, _ = strconv.ParseBool(snowplowData.BrAg) event.BrCookies, _ = strconv.ParseBool(snowplowData.BrCookies) // Bind screen resolutions event.BrViewWidth = snowplowData.BrView.Width event.BrViewHeight = snowplowData.BrView.Height event.DvceScreenWidth = snowplowData.DvceScreen.Width event.DvceScreenHeight = snowplowData.DvceScreen.Height event.DocWidth = snowplowData.Doc.Width event.DocHeight = snowplowData.Doc.Width // Bind time values event.DvceTstamp = snowplowData.DvceTstamp.Time // Bind Geo values geoIPRecord := geo.GetRecord(snowplowRequest.IPAddress) if geoIPRecord != nil { checkStringForNull(geoIPRecord.CountryName, &event.GeoCountry) checkStringForNull(geoIPRecord.Region, &event.GeoRegion) checkStringForNull(geoIPRecord.City, &event.GeoCity) checkStringForNull(geoIPRecord.PostalCode, &event.GeoZipcode) event.GeoLatitude = geoIPRecord.Latitude event.GeoLongtitude = geoIPRecord.Longitude checkStringForNull(geoIPRecord.Region, &event.GeoRegionName) } // Bind useragent values ua := user_agent.New(snowplowRequest.Useragent) event.DvceIsMobile = ua.Mobile() checkStringForNull(ua.OS(), &event.OsName) checkStringForNull(ua.Platform(), &event.DvceType) name, version := ua.Engine() checkStringForNull(name+version, &event.BrRndrNgn) name, version = ua.Browser() checkStringForNull(name, &event.BrName) checkStringForNull(version, &event.BrVersion) // Bind contexts if len(snowplowData.Contexts) > 0 { contextsField := &SnowplowContextsJsonField{} err := json.Unmarshal([]byte(snowplowData.Contexts), &contextsField) if err != nil { return err } else { rawContexts := contextsField.Data[0] rawContexts = rawContexts[8 : len(rawContexts)-1] // is json? var js interface{} err := json.Unmarshal([]byte(rawContexts), &js) if err != nil { rawContexts = contextsField.Data[0] } checkStringForNull(string(rawContexts), &event.Contexts) } contexts := &SnowplowContexts{} err = json.Unmarshal([]byte(snowplowData.Contexts), &contexts) if err != nil { return err } else { contextsData := contexts.Data[0].Data checkStringForNull(contextsData.UtmCampaign, &event.UtmCampaign) checkStringForNull(contextsData.UtmContent, &event.UtmContent) checkStringForNull(contextsData.UtmTerm, &event.UtmTerm) checkStringForNull(contextsData.UtmSource, &event.UtmSource) checkStringForNull(contextsData.UtmMedium, &event.UtmMedium) } } else { event.Contexts.Valid = false } // Bind unstructured event if len(snowplowData.UnstructEvent) > 0 { checkStringForNull(snowplowData.UnstructEvent, &event.UnstructEvent) } return nil }
func send_auditlog_record(msg jsonMsg) { //fmt.Println(msg) params := url.Values{} /* struct based implementation */ if msg.Action != "" { params.Set("action", msg.Action) } else { action := []string{} for _, s := range []string{ msg.Study, msg.Subset1, msg.Subset2, msg.Analysis, msg.Query, msg.FacetQuery, msg.User} { if s != "0" && s != "" { action = append(action, s) } } params.Set("action", strings.Join(action, "|")) } if msg.Application != "" { params.Set("application", msg.Application) } if msg.AppVersion != "" { params.Set("appVersion", msg.AppVersion) } if msg.User != "" { params.Set("user", msg.User) } if msg.Task != "" { params.Set("task", msg.Task) } if msg.Browser != "" { browser, version := user_agent.New(msg.Browser).Browser() params.Set("browser", browser+" "+version) } /**/ /* alternative map based implementation for _, k := range []string{"action", "program", "programVersion", "user", "event"} { if _, hasKey := msg[k]; !hasKey { continue } key := k if outkey, translate := keyMap[k]; translate { key = outkey } params.Set(key, fmt.Sprintf("%v", msg[k])) } if _, hasKey := msg["action"]; !hasKey { action := []string{} for _, s := range []string{msg["study"], msg["subset1"], msg["subset2"]; msg["analysis"], msg["query"], msg["facetQuery"], msg["User"]} { if s != "0" && s != "" { action = append(action, s) } } params.Set("action", strings.Join(action, "|")) } if _, hasKey := msg["userAgent"]; hasKey { browser, version := user_agent.New(msg["userAgent"]).Browser() params.Set("browser", browser + " " + version) } */ fullurl := URL + "?" + params.Encode() //fmt.Println(fullurl) resp, err := http.PostForm(fullurl, url.Values{}) if err != nil { error("WARNING: Failed to post message to metrics server: " + err.Error()) } else { ioutil.ReadAll(resp.Body) resp.Body.Close() } atomicAdd(&requests_in_progress, -1) wg.Done() }
// User MUST be validated before calling Login func Login(c *Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) { c.LogAuditWithUserId(user.Id, "attempt") if !user.EmailVerified && utils.Cfg.EmailSettings.RequireEmailVerification { c.Err = model.NewAppError("Login", "Login failed because email address has not been verified", "user_id="+user.Id) c.Err.StatusCode = http.StatusForbidden return } if user.DeleteAt > 0 { c.Err = model.NewAppError("Login", "Login failed because your account has been set to inactive. Please contact an administrator.", "user_id="+user.Id) c.Err.StatusCode = http.StatusForbidden return } session := &model.Session{UserId: user.Id, TeamId: user.TeamId, Roles: user.Roles, DeviceId: deviceId, IsOAuth: false} maxAge := model.SESSION_TIME_WEB_IN_SECS if len(deviceId) > 0 { session.SetExpireInDays(model.SESSION_TIME_MOBILE_IN_DAYS) maxAge = model.SESSION_TIME_MOBILE_IN_SECS } else { session.SetExpireInDays(model.SESSION_TIME_WEB_IN_DAYS) } ua := user_agent.New(r.UserAgent()) plat := ua.Platform() if plat == "" { plat = "unknown" } os := ua.OS() if os == "" { os = "unknown" } bname, bversion := ua.Browser() if bname == "" { bname = "unknown" } if bversion == "" { bversion = "0.0" } session.AddProp(model.SESSION_PROP_PLATFORM, plat) session.AddProp(model.SESSION_PROP_OS, os) session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion)) if result := <-Srv.Store.Session().Save(session); result.Err != nil { c.Err = result.Err c.Err.StatusCode = http.StatusForbidden return } else { session = result.Data.(*model.Session) AddSessionToCache(session) } w.Header().Set(model.HEADER_TOKEN, session.Token) tokens := GetMultiSessionCookieTokens(r) multiToken := "" seen := make(map[string]string) seen[session.TeamId] = session.TeamId for _, token := range tokens { s := GetSession(token) if s != nil && !s.IsExpired() && seen[s.TeamId] == "" { multiToken += " " + token seen[s.TeamId] = s.TeamId } } multiToken = strings.TrimSpace(multiToken + " " + session.Token) multiSessionCookie := &http.Cookie{ Name: model.SESSION_COOKIE_TOKEN, Value: multiToken, Path: "/", MaxAge: maxAge, HttpOnly: true, } http.SetCookie(w, multiSessionCookie) c.Session = *session c.LogAuditWithUserId(user.Id, "success") }
func ParseUserAgent(useragent string) (string, string) { ua := user_agent.New(useragent) return ua.Browser() }
func RepoAssignment(redirect bool, args ...bool) macaron.Handler { return func(ctx *Context) { var ( displayBare bool // To display bare page if it is a bare repo. ) if len(args) >= 1 { displayBare = args[0] } var ( u *models.User err error ) userName := ctx.Params(":username") repoName := ctx.Params(":reponame") refName := ctx.Params(":branchname") if len(refName) == 0 { refName = ctx.Params(":path") } // Check if the user is the same as the repository owner if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) { u = ctx.User } else { u, err = models.GetUserByName(userName) if err != nil { if models.IsErrUserNotExist(err) { ctx.Handle(404, "GetUserByName", err) } else { ctx.Handle(500, "GetUserByName", err) } return } } ctx.Repo.Owner = u // Get repository. repo, err := models.GetRepositoryByName(u.Id, repoName) if err != nil { if models.IsErrRepoNotExist(err) { ctx.Handle(404, "GetRepositoryByName", err) } else { ctx.Handle(500, "GetRepositoryByName", err) } return } else if err = repo.GetOwner(); err != nil { ctx.Handle(500, "GetOwner", err) return } mode, err := models.AccessLevel(ctx.User, repo) if err != nil { ctx.Handle(500, "AccessLevel", err) return } ctx.Repo.AccessMode = mode // Check access. if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { ctx.Handle(404, "no access right", err) return } ctx.Data["HasAccess"] = true if repo.IsMirror { ctx.Repo.Mirror, err = models.GetMirror(repo.ID) if err != nil { ctx.Handle(500, "GetMirror", err) return } ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval } ctx.Repo.Repository = repo ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) if err != nil { ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) return } ctx.Repo.GitRepo = gitRepo ctx.Repo.RepoLink, err = repo.RepoLink() if err != nil { ctx.Handle(500, "RepoLink", err) return } ctx.Data["RepoLink"] = ctx.Repo.RepoLink ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name tags, err := ctx.Repo.GitRepo.GetTags() if err != nil { ctx.Handle(500, "GetTags", err) return } ctx.Data["Tags"] = tags ctx.Repo.Repository.NumTags = len(tags) if repo.IsFork { RetrieveBaseRepo(ctx, repo) if ctx.Written() { return } } ctx.Data["Title"] = u.Name + "/" + repo.Name ctx.Data["Repository"] = repo ctx.Data["Owner"] = ctx.Repo.Repository.Owner ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner() ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin() ctx.Data["DisableSSH"] = setting.DisableSSH ctx.Repo.CloneLink, err = repo.CloneLink() if err != nil { ctx.Handle(500, "CloneLink", err) return } ctx.Data["CloneLink"] = ctx.Repo.CloneLink if ctx.Query("go-get") == "1" { ctx.Data["GoGetImport"] = fmt.Sprintf("%s/%s/%s", setting.Domain, u.Name, repo.Name) } if ctx.IsSigned { ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.Id, repo.ID) ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.Id, repo.ID) } // repo is bare and display enable if ctx.Repo.Repository.IsBare { log.Debug("Bare repository: %s", ctx.Repo.RepoLink) // NOTE: to prevent templating error ctx.Data["BranchName"] = "" if displayBare { if !ctx.Repo.IsAdmin() { ctx.Flash.Info(ctx.Tr("repo.repo_is_empty"), true) } ctx.HTML(200, "repo/bare") } return } ctx.Data["TagName"] = ctx.Repo.TagName brs, err := ctx.Repo.GitRepo.GetBranches() if err != nil { ctx.Handle(500, "GetBranches", err) return } ctx.Data["Branches"] = brs ctx.Data["BrancheCount"] = len(brs) // If not branch selected, try default one. // If default branch doesn't exists, fall back to some other branch. if len(ctx.Repo.BranchName) == 0 { if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) { ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch } else if len(brs) > 0 { ctx.Repo.BranchName = brs[0] } } ctx.Data["BranchName"] = ctx.Repo.BranchName ctx.Data["CommitID"] = ctx.Repo.CommitID userAgent := ctx.Req.Header.Get("User-Agent") ua := user_agent.New(userAgent) browserName, browserVer := ua.Browser() ctx.Data["BrowserSupportsCopy"] = (browserName == "Chrome" && version.Compare(browserVer, CHROME_COPY_SUPPORT, ">=")) || (browserName == "Firefox" && version.Compare(browserVer, FIREFOX_COPY_SUPPORT, ">=")) } }
func getFile(c *Context, w http.ResponseWriter, r *http.Request) { if len(utils.Cfg.FileSettings.DriverName) == 0 { c.Err = model.NewLocAppError("uploadFile", "api.file.upload_file.storage.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } params := mux.Vars(r) channelId := params["channel_id"] if len(channelId) != 26 { c.SetInvalidParam("getFile", "channel_id") return } userId := params["user_id"] if len(userId) != 26 { c.SetInvalidParam("getFile", "user_id") return } filename := params["filename"] if len(filename) == 0 { c.SetInvalidParam("getFile", "filename") return } hash := r.URL.Query().Get("h") data := r.URL.Query().Get("d") teamId := r.URL.Query().Get("t") isDownload := r.URL.Query().Get("download") == "1" cchan := Srv.Store.Channel().CheckPermissionsTo(c.Session.TeamId, channelId, c.Session.UserId) path := "" if len(teamId) == 26 { path = "teams/" + teamId + "/channels/" + channelId + "/users/" + userId + "/" + filename } else { path = "teams/" + c.Session.TeamId + "/channels/" + channelId + "/users/" + userId + "/" + filename } fileData := make(chan []byte) getFileAndForget(path, fileData) if len(hash) > 0 && len(data) > 0 && len(teamId) == 26 { if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.FileSettings.PublicLinkSalt)) { c.Err = model.NewLocAppError("getFile", "api.file.get_file.public_invalid.app_error", nil, "") return } } else if !c.HasPermissionsToChannel(cchan, "getFile") { return } f := <-fileData if f == nil { c.Err = model.NewLocAppError("getFile", "api.file.get_file.not_found.app_error", nil, "path="+path) c.Err.StatusCode = http.StatusNotFound return } w.Header().Set("Cache-Control", "max-age=2592000, public") w.Header().Set("Content-Length", strconv.Itoa(len(f))) w.Header().Del("Content-Type") // Content-Type will be set automatically by the http writer if isDownload { // attach extra headers to trigger a download on IE, Edge, and Safari ua := user_agent.New(r.UserAgent()) bname, _ := ua.Browser() parts := strings.Split(filename, "/") filePart := strings.Split(parts[len(parts)-1], "?")[0] w.Header().Set("Content-Disposition", "attachment;filename=\""+filePart+"\"") if bname == "Edge" || bname == "Internet Explorer" || bname == "Safari" { // trim off anything before the final / so we just get the file's name w.Header().Set("Content-Type", "application/octet-stream") } } w.Write(f) }
// User MUST be validated before calling Login func Login(c *Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) { c.LogAuditWithUserId(user.Id, "attempt") if !user.EmailVerified && !utils.Cfg.EmailSettings.ByPassEmail { c.Err = model.NewAppError("Login", "Login failed because email address has not been verified", "user_id="+user.Id) c.Err.StatusCode = http.StatusForbidden return } if user.DeleteAt > 0 { c.Err = model.NewAppError("Login", "Login failed because your account has been set to inactive. Please contact an administrator.", "user_id="+user.Id) c.Err.StatusCode = http.StatusForbidden return } session := &model.Session{UserId: user.Id, TeamId: user.TeamId, Roles: user.Roles, DeviceId: deviceId} maxAge := model.SESSION_TIME_WEB_IN_SECS if len(deviceId) > 0 { session.SetExpireInDays(model.SESSION_TIME_MOBILE_IN_DAYS) maxAge = model.SESSION_TIME_MOBILE_IN_SECS } else { session.SetExpireInDays(model.SESSION_TIME_WEB_IN_DAYS) } ua := user_agent.New(r.UserAgent()) plat := ua.Platform() if plat == "" { plat = "unknown" } os := ua.OS() if os == "" { os = "unknown" } bname, bversion := ua.Browser() if bname == "" { bname = "unknown" } if bversion == "" { bversion = "0.0" } session.AddProp(model.SESSION_PROP_PLATFORM, plat) session.AddProp(model.SESSION_PROP_OS, os) session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion)) if result := <-Srv.Store.Session().Save(session); result.Err != nil { c.Err = result.Err c.Err.StatusCode = http.StatusForbidden return } else { session = result.Data.(*model.Session) sessionCache.Add(session.Id, session) } w.Header().Set(model.HEADER_TOKEN, session.Id) sessionCookie := &http.Cookie{ Name: model.SESSION_TOKEN, Value: session.Id, Path: "/", MaxAge: maxAge, HttpOnly: true, } http.SetCookie(w, sessionCookie) c.Session = *session c.LogAuditWithUserId(user.Id, "success") }
func getFile(c *Context, w http.ResponseWriter, r *http.Request) { if len(utils.Cfg.FileSettings.DriverName) == 0 { c.Err = model.NewAppError("uploadFile", "Unable to get file. Image storage is not configured.", "") c.Err.StatusCode = http.StatusNotImplemented return } params := mux.Vars(r) channelId := params["channel_id"] if len(channelId) != 26 { c.SetInvalidParam("getFile", "channel_id") return } userId := params["user_id"] if len(userId) != 26 { c.SetInvalidParam("getFile", "user_id") return } filename := params["filename"] if len(filename) == 0 { c.SetInvalidParam("getFile", "filename") return } hash := r.URL.Query().Get("h") data := r.URL.Query().Get("d") teamId := r.URL.Query().Get("t") cchan := Srv.Store.Channel().CheckPermissionsTo(c.Session.TeamId, channelId, c.Session.UserId) path := "" if len(teamId) == 26 { path = "teams/" + teamId + "/channels/" + channelId + "/users/" + userId + "/" + filename } else { path = "teams/" + c.Session.TeamId + "/channels/" + channelId + "/users/" + userId + "/" + filename } fileData := make(chan []byte) getFileAndForget(path, fileData) if len(hash) > 0 && len(data) > 0 && len(teamId) == 26 { if !model.ComparePassword(hash, fmt.Sprintf("%v:%v", data, utils.Cfg.FileSettings.PublicLinkSalt)) { c.Err = model.NewAppError("getFile", "The public link does not appear to be valid", "") return } props := model.MapFromJson(strings.NewReader(data)) t, err := strconv.ParseInt(props["time"], 10, 64) if err != nil || model.GetMillis()-t > 1000*60*60*24*7 { // one week c.Err = model.NewAppError("getFile", "The public link has expired", "") return } } else if !c.HasPermissionsToChannel(cchan, "getFile") { return } f := <-fileData if f == nil { c.Err = model.NewAppError("getFile", "Could not find file.", "path="+path) c.Err.StatusCode = http.StatusNotFound return } w.Header().Set("Cache-Control", "max-age=2592000, public") w.Header().Set("Content-Length", strconv.Itoa(len(f))) w.Header().Del("Content-Type") // Content-Type will be set automatically by the http writer // attach extra headers to trigger a download on IE, Edge, and Safari ua := user_agent.New(r.UserAgent()) bname, _ := ua.Browser() if bname == "Edge" || bname == "Internet Explorer" || bname == "Safari" { // trim off anything before the final / so we just get the file's name parts := strings.Split(filename, "/") w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", "attachment;filename=\""+parts[len(parts)-1]+"\"") } w.Write(f) }
func login(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) extraInfo := "" var result store.StoreResult if len(props["id"]) != 0 { extraInfo = props["id"] if result = <-Srv.Store.User().Get(props["id"]); result.Err != nil { c.Err = result.Err return } } var team *model.Team if result.Data == nil && len(props["email"]) != 0 && len(props["domain"]) != 0 { extraInfo = props["email"] + " in " + props["domain"] if nr := <-Srv.Store.Team().GetByDomain(props["domain"]); nr.Err != nil { c.Err = nr.Err return } else { team = nr.Data.(*model.Team) if result = <-Srv.Store.User().GetByEmail(team.Id, props["email"]); result.Err != nil { c.Err = result.Err return } } } if result.Data == nil { c.Err = model.NewAppError("login", "Login failed because we couldn't find a valid account", extraInfo) c.Err.StatusCode = http.StatusBadRequest return } user := result.Data.(*model.User) if team == nil { if tResult := <-Srv.Store.Team().Get(user.TeamId); tResult.Err != nil { c.Err = tResult.Err return } else { team = tResult.Data.(*model.Team) } } c.LogAuditWithUserId(user.Id, "attempt") if !model.ComparePassword(user.Password, props["password"]) { c.LogAuditWithUserId(user.Id, "fail") c.Err = model.NewAppError("login", "Login failed because of invalid password", extraInfo) c.Err.StatusCode = http.StatusForbidden return } if !user.EmailVerified { c.Err = model.NewAppError("login", "Login failed because email address has not been verified", extraInfo) c.Err.StatusCode = http.StatusForbidden return } if user.DeleteAt > 0 { c.Err = model.NewAppError("login", "Login failed because your account has been set to inactive. Please contact an administrator.", extraInfo) c.Err.StatusCode = http.StatusForbidden return } session := &model.Session{UserId: user.Id, TeamId: team.Id, Roles: user.Roles, DeviceId: props["device_id"]} maxAge := model.SESSION_TIME_WEB_IN_SECS if len(props["device_id"]) > 0 { session.SetExpireInDays(model.SESSION_TIME_MOBILE_IN_DAYS) maxAge = model.SESSION_TIME_MOBILE_IN_SECS } else { session.SetExpireInDays(model.SESSION_TIME_WEB_IN_DAYS) } ua := user_agent.New(r.UserAgent()) plat := ua.Platform() if plat == "" { plat = "unknown" } os := ua.OS() if os == "" { os = "unknown" } bname, bversion := ua.Browser() if bname == "" { bname = "unknown" } if bversion == "" { bversion = "0.0" } session.AddProp(model.SESSION_PROP_PLATFORM, plat) session.AddProp(model.SESSION_PROP_OS, os) session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion)) if result := <-Srv.Store.Session().Save(session); result.Err != nil { c.Err = result.Err c.Err.StatusCode = http.StatusForbidden return } else { session = result.Data.(*model.Session) sessionCache.Add(session.Id, session) } w.Header().Set(model.HEADER_TOKEN, session.Id) sessionCookie := &http.Cookie{ Name: model.SESSION_TOKEN, Value: session.Id, Path: "/", MaxAge: maxAge, HttpOnly: true, } http.SetCookie(w, sessionCookie) user.Sanitize(map[string]bool{}) c.Session = *session c.LogAuditWithUserId(user.Id, "success") w.Write([]byte(result.Data.(*model.User).ToJson())) }