예제 #1
0
//Create a student.
func (r *studentRouter) Create(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		err  error
		s, _ = ctx.Value("services").(*services.Services)

		payload struct {
			FirstName string
			LastName  string
			Status    int
		}
	)

	if err = httputils.DecodeJSON(req.Body, &payload); err != nil {
		httputils.WriteError(w, http.StatusBadRequest, "")
		return nil
	}

	student := &models.Student{
		FirstName: payload.FirstName,
		LastName:  payload.LastName,
		Status:    payload.Status,
	}

	err = s.Student.Create(student)
	if err != nil {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, nil)
}
예제 #2
0
// createStaticFilesServer creates a static file server to server all of the
// frontend files (html, js, css, etc).
func (s *Server) createStaticFilesServer() {
	var (
		adminAppPath    = s.cfg.App.Frontend.Admin
		staticFilesPath = path.Join(adminAppPath, "static")
	)

	contextHandler := func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
		file := path.Join(staticFilesPath, req.URL.Path)

		http.ServeFile(w, req, file)
		return nil
	}

	contextHandler = router.NoDirListing(router.GzipContent(contextHandler))

	handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := context.Background()
		err := contextHandler(ctx, w, req)

		if err != nil {
			log.Printf("static file handler [%s][%s] returned error: %s", req.Method, req.URL.Path, err)
			httputils.WriteError(w, http.StatusInternalServerError, "")
		}
	})

	s.muxRouter.
		PathPrefix("/static/").
		Handler(http.StripPrefix("/static/", handler))
}
예제 #3
0
// Change the logged user's full name.
func (r *userRouter) ChangeFullNameForCurrentUser(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		err            error
		s, _           = ctx.Value("services").(*services.Services)
		sessionData, _ = ctx.Value("sessionData").(*router.SessionData)

		payload struct {
			FirstName string
			LastName  string
		}
	)

	if err = httputils.DecodeJSON(req.Body, &payload); err != nil {
		httputils.WriteError(w, http.StatusBadRequest, "")
		return nil
	}

	err = s.User.ChangeFullName(sessionData.UserId, payload.FirstName, payload.LastName)

	if err != nil && err != services.RecordNotFound {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, nil)
}
예제 #4
0
func (r *userRouter) FindById(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		err    error
		userId int
		s, _   = ctx.Value("services").(*services.Services)
		vars   = mux.Vars(req)
	)

	type MappedUser struct {
		Id        int    `json:"id"`
		Username  string `json:"username"`
		Email     string `json:"email"`
		FirstName string `json:"firstName"`
		LastName  string `json:"lastName"`
		Status    int    `json:"status"`
		IsAdmin   bool   `json:"isAdmin"`
		IsTeacher bool   `json:"isTeacher"`
	}

	userId, err = strconv.Atoi(vars["id"])

	if err != nil {
		httputils.WriteError(w, http.StatusBadRequest, "")
		return err
	}

	user, err := s.User.FindById(userId)
	if err != nil {
		return err
	} else if user == nil {
		httputils.WriteError(w, http.StatusNotFound, "")
		return nil
	}

	response := &MappedUser{
		Id:        user.Id,
		Username:  user.Username,
		Email:     user.Email,
		FirstName: user.FirstName,
		LastName:  user.LastName,
		Status:    user.Status,
		IsAdmin:   user.IsAdmin,
		IsTeacher: user.IsTeacher,
	}

	return httputils.WriteJSON(w, http.StatusOK, response)
}
예제 #5
0
// Find Student by id.
func (r *studentRouter) FindById(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		err       error
		studentId int
		s, _      = ctx.Value("services").(*services.Services)
		vars      = mux.Vars(req)
	)

	type MappedStudent struct {
		Id        int       `json:"id"`
		Email     string    `json:"email"`
		FirstName string    `json:"firstName"`
		LastName  string    `json:"lastName"`
		Status    int       `json:"status"`
		CreatedAt time.Time `json:"createdAt"`
	}

	studentId, err = strconv.Atoi(vars["id"])

	if err != nil {
		httputils.WriteError(w, http.StatusBadRequest, "")
		return err
	}

	student, err := s.Student.FindById(studentId)
	if err != nil {
		return err
	} else if student == nil {
		httputils.WriteError(w, http.StatusNotFound, "")
		return nil
	}

	response := &MappedStudent{
		Id:        student.Id,
		Email:     student.Email,
		FirstName: student.FirstName,
		LastName:  student.LastName,
		Status:    student.Status,
		CreatedAt: student.CreatedAt,
	}

	return httputils.WriteJSON(w, http.StatusOK, response)
}
예제 #6
0
// Edit a user.
func (r *userRouter) Edit(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		err  error
		s, _ = ctx.Value("services").(*services.Services)

		payload struct {
			Id        int
			Username  string
			Email     string
			FirstName string
			LastName  string
			Status    int
			IsAdmin   bool
			IsTeacher bool
		}
	)

	type Response struct {
		Success      bool   `json:"success"`
		ErrorMessage string `json:"errorMessage"`
	}

	if err = httputils.DecodeJSON(req.Body, &payload); err != nil {
		httputils.WriteError(w, http.StatusBadRequest, "")
		return nil
	}

	user := &models.User{
		Id:        payload.Id,
		Username:  payload.Username,
		Email:     payload.Email,
		FirstName: payload.FirstName,
		LastName:  payload.LastName,
		Status:    payload.Status,
		IsAdmin:   payload.IsAdmin,
		IsTeacher: payload.IsTeacher,
	}

	err = s.User.Edit(user)
	if err != nil {
		if err == services.DuplicateUsernameError {
			return httputils.WriteJSON(w, http.StatusOK, &Response{
				Success:      false,
				ErrorMessage: "El nombre de usuario ya existe!",
			})
		}

		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, &Response{
		Success: true,
	})
}
예제 #7
0
// HandleError sets the appropriate headers to the response if a http handler
// returned an error. This might be used in the future if different types of
// errors are returned.
func HandleHttpError(h httputils.ContextHandler) httputils.ContextHandler {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		err := h(ctx, w, r)

		if err != nil {
			httputils.WriteError(w, http.StatusInternalServerError, "")
		}

		return err
	}
}
예제 #8
0
// Basic email/password login.
// Checks:
// 		- User must exist
//		- Passwords match
//		- User's status is Active
//
// If the checks pass, it sets up a session cookie.
func (r *authRouter) Login(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		s, _        = ctx.Value("services").(*services.Services)
		cookieStore = ctx.Value("cookieStore").(*sessions.CookieStore)
		err         error

		loginForm struct {
			Identifier string
			Password   string
		}
	)

	if err = httputils.DecodeJSON(req.Body, &loginForm); err != nil {
		httputils.WriteError(w, http.StatusBadRequest, "")
		return nil
	}

	user, err := s.Auth.BasicAuth(loginForm.Identifier, loginForm.Password)
	if err != nil {
		httputils.WriteError(w, http.StatusInternalServerError, "")
		return nil
	} else if user == nil {
		httputils.WriteError(w, http.StatusUnauthorized, "Usuario/clave inválidos")
		return nil
	}

	session, _ := cookieStore.New(req, router.SessionCookieName)
	session.Values["data"] = &router.SessionData{
		UserId:    user.Id,
		Email:     user.Email,
		IsAdmin:   user.IsAdmin,
		IsTeacher: user.IsTeacher,
	}
	session.Save(req, w)

	return nil
}
예제 #9
0
// Basic session logout. If the session cookie is set, it sets its MaxAge=-1
// to delete it, else, well he's already out.
func (r *authRouter) Logout(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		cookieStore = ctx.Value("cookieStore").(*sessions.CookieStore)
		err         error
	)
	session, err := cookieStore.Get(req, router.SessionCookieName)

	if err != nil {
		httputils.WriteError(w, http.StatusUnauthorized, "")
		return err
	}

	session.Options.MaxAge = -1
	session.Save(req, w)
	return nil
}
예제 #10
0
// Retrieve logged user's information.
func (r *userRouter) GetProfileForCurrentUser(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		s, _           = ctx.Value("services").(*services.Services)
		sessionData, _ = ctx.Value("sessionData").(*router.SessionData)
	)

	type Response struct {
		Id        int    `json:"id"`
		Username  string `json:"username"`
		Email     string `json:"email"`
		FirstName string `json:"firstName"`
		LastName  string `json:"lastName"`
		Status    int    `json:"status"`
		IsAdmin   bool   `json:"isAdmin"`
		IsTeacher bool   `json:"isTeacher"`
	}

	user, err := s.User.FindById(sessionData.UserId)

	if err != nil {
		return err
	} else if user == nil {
		httputils.WriteError(w, http.StatusNotFound, "")
		return nil
	}

	response := &Response{
		Id:        user.Id,
		Username:  user.Username,
		Email:     user.Email,
		FirstName: user.FirstName,
		LastName:  user.LastName,
		Status:    user.Status,
		IsAdmin:   user.IsAdmin,
		IsTeacher: user.IsTeacher,
	}

	return httputils.WriteJSON(w, http.StatusOK, response)
}
예제 #11
0
// Delete user.
func (r *userRouter) Delete(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		err  error
		s, _ = ctx.Value("services").(*services.Services)

		payload struct {
			UserId int
		}
	)

	if err = httputils.DecodeJSON(req.Body, &payload); err != nil {
		httputils.WriteError(w, http.StatusBadRequest, "")
		return nil
	}

	err = s.User.Delete(payload.UserId)
	if err != nil {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, nil)
}
예제 #12
0
// Change a user's password.
func (r *userRouter) ChangePassword(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
	var (
		err  error
		s, _ = ctx.Value("services").(*services.Services)

		payload struct {
			UserId      int
			NewPassword string
		}
	)

	if err = httputils.DecodeJSON(req.Body, &payload); err != nil {
		httputils.WriteError(w, http.StatusBadRequest, "")
		return nil
	}

	err = s.User.ChangePassword(payload.UserId, payload.NewPassword)
	if err != nil && err != services.RecordNotFound {
		return err
	}

	return httputils.WriteJSON(w, http.StatusOK, nil)
}