Skouter mortgage estimates. Web application with view written in PHP and Vue, but controller and models in Go.
 
 
 
 
 
 

4097 lines
84 KiB

  1. package main
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/base64"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. _ "github.com/go-sql-driver/mysql"
  10. "html/template"
  11. "io"
  12. "log"
  13. "math"
  14. "net/http"
  15. "net/http/httputil"
  16. "net/mail"
  17. "net/url"
  18. "net/smtp"
  19. "os"
  20. "os/exec"
  21. "regexp"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. // pdf "github.com/SebastiaanKlippert/go-wkhtmltopdf"
  27. "github.com/brianvoe/gofakeit/v6"
  28. "github.com/disintegration/gift"
  29. "github.com/dustin/go-humanize"
  30. "github.com/golang-jwt/jwt/v4"
  31. "github.com/stripe/stripe-go/v76"
  32. "github.com/stripe/stripe-go/v76/customer"
  33. "github.com/stripe/stripe-go/v76/subscription"
  34. // "github.com/stripe/stripe-go/v76/invoice"
  35. // "github.com/stripe/stripe-go/v76/paymentintent"
  36. "github.com/stripe/stripe-go/v76/webhook"
  37. "image"
  38. _ "image/jpeg"
  39. "image/png"
  40. )
  41. type Config struct {
  42. DBName string
  43. DBUsername string
  44. DBPassword string
  45. }
  46. type Address struct {
  47. Id int `json:"id"`
  48. Full string `json:"full"`
  49. Street string `json:"street"`
  50. City string `json:"city"`
  51. Region string `json:"region"`
  52. Country string `json:"country"`
  53. Zip string `json:"zip"`
  54. }
  55. type Branch struct {
  56. Id int `json:"id"`
  57. Name string `json:"name"`
  58. Type string `json:"type"`
  59. Letterhead []byte `json:"letterhead"`
  60. Num string `json:"num"`
  61. Phone string `json:"phone"`
  62. Address Address `json:"address"`
  63. }
  64. type Subscription struct {
  65. Id int `json:"id"`
  66. UserId int `json:"userId"`
  67. StripeId string `json:"stripeId"`
  68. CustomerId string `json:"customerId"`
  69. PriceId string `json:"priceId"`
  70. Start int `json:"start"`
  71. End int `json:"end"`
  72. ClientSecret string `json:"clientSecret,omitempty"`
  73. PaymentStatus string `json:"paymentStatus"`
  74. Status string `json:"status"`
  75. }
  76. type User struct {
  77. Id int `json:"id"`
  78. Email string `json:"email"`
  79. FirstName string `json:"firstName"`
  80. LastName string `json:"lastName"`
  81. Phone string `json:"phone"`
  82. Address Address `json:"address"`
  83. Branch Branch `json:"branch"`
  84. License License `json:"license"`
  85. Sub Subscription `json:"sub"`
  86. Status string `json:"status"`
  87. Country string `json:"country"`
  88. Title string `json:"title"`
  89. Verified bool `json:"verified"`
  90. Role string `json:"role"`
  91. Password string `json:"password,omitempty"`
  92. CustomerId string `json:"customerId"`
  93. }
  94. type License struct {
  95. Id int `json:"id"`
  96. UserId int `json:"userId"`
  97. Type string `json:"type"`
  98. Num string `json:"num"`
  99. }
  100. type UserClaims struct {
  101. Id int `json:"id"`
  102. Role string `json:"role"`
  103. Exp string `json:"exp"`
  104. }
  105. type VerificationClaims struct {
  106. Id int `json:"id"`
  107. Exp string `json:"exp"`
  108. }
  109. type Page struct {
  110. tpl *template.Template
  111. Title string
  112. Name string
  113. }
  114. type Borrower struct {
  115. Id int `json:"id"`
  116. Credit int `json:"credit"`
  117. Income int `json:"income"`
  118. Num int `json:"num"`
  119. }
  120. type FeeTemplate struct {
  121. Id int `json:"id"`
  122. User int `json:"user"`
  123. Branch int `json:"branch"`
  124. Amount int `json:"amount"`
  125. Perc float32 `json:"perc"`
  126. Type string `json:"type"`
  127. Notes string `json:"notes"`
  128. Name string `json:"name"`
  129. Category string `json:"category"`
  130. Auto bool `json:"auto"`
  131. }
  132. type Fee struct {
  133. Id int `json:"id"`
  134. LoanId int `json:"loan_id"`
  135. Amount int `json:"amount"`
  136. Perc float32 `json:"perc"`
  137. Type string `json:"type"`
  138. Notes string `json:"notes"`
  139. Name string `json:"name"`
  140. Category string `json:"category"`
  141. }
  142. type LoanType struct {
  143. Id int `json:"id"`
  144. User int `json:"user"`
  145. Branch int `json:"branch"`
  146. Name string `json:"name"`
  147. }
  148. type Loan struct {
  149. Id int `json:"id"`
  150. EstimateId int `json:"estimateId"`
  151. Type LoanType `json:"type"`
  152. Amount int `json:"amount"`
  153. Amortization string `json:"amortization"`
  154. Term int `json:"term"`
  155. Ltv float32 `json:"ltv"`
  156. Dti float32 `json:"dti"`
  157. Hoi int `json:"hoi"`
  158. Hazard int `json:"hazard"`
  159. Tax int `json:"tax"`
  160. Interest float32 `json:"interest"`
  161. Mi MI `json:"mi"`
  162. Fees []Fee `json:"fees"`
  163. Credits []Fee // Fees with negative amounts for internal use
  164. Name string `json:"title"`
  165. Result Result `json:"result"`
  166. }
  167. type MI struct {
  168. Type string `json:"user"`
  169. Label string `json:"label"`
  170. Lender string `json:"lender"`
  171. Rate float32 `json:"rate"`
  172. Premium int `json:"premium"`
  173. Upfront int `json:"upfront"`
  174. Monthly bool `json:"monthly"`
  175. FiveYearTotal float32 `json:"fiveYearTotal"`
  176. InitialAllInPremium float32 `json:"initialAllInPremium"`
  177. InitialAllInRate float32 `json:"initialAllInRate"`
  178. InitialAmount float32 `json:"initialAmount"`
  179. }
  180. type Result struct {
  181. Id int `json:"id"`
  182. LoanId int `json:"loanId"`
  183. LoanPayment int `json:"loanPayment"`
  184. TotalMonthly int `json:"totalMonthly"`
  185. TotalFees int `json:"totalFees"`
  186. TotalCredits int `json:"totalCredits"`
  187. CashToClose int `json:"cashToClose"`
  188. }
  189. type Estimate struct {
  190. Id int `json:"id"`
  191. User int `json:"user"`
  192. Borrower Borrower `json:"borrower"`
  193. Transaction string `json:"transaction"`
  194. Price int `json:"price"`
  195. Property string `json:"property"`
  196. Occupancy string `json:"occupancy"`
  197. Zip string `json:"zip"`
  198. Pud bool `json:"pud"`
  199. Loans []Loan `json:"loans"`
  200. }
  201. type ETemplate struct {
  202. Id int `json:"id"`
  203. Estimate Estimate `json:"estimate"`
  204. UserId int `json:"userId"`
  205. BranchId int `json:"branchId"`
  206. }
  207. type Report struct {
  208. Title string
  209. Name string
  210. Avatar string
  211. Letterhead string
  212. User User
  213. Estimate Estimate
  214. }
  215. type Password struct {
  216. Old string `json:"old"`
  217. New string `json:"new"`
  218. }
  219. type Endpoint func(http.ResponseWriter, *sql.DB, *http.Request)
  220. type HookKeys struct {
  221. InvoicePaid string
  222. InvoiceFailed string
  223. SubCreated string
  224. SubUpdated string
  225. SubDeleted string
  226. }
  227. var (
  228. regexen = make(map[string]*regexp.Regexp)
  229. relock sync.Mutex
  230. address = "localhost:8001"
  231. mainAddress = "localhost:8002"
  232. )
  233. var paths = map[string]string{
  234. "home": "views/home.tpl",
  235. "terms": "views/terms.tpl",
  236. "app": "views/app.tpl",
  237. "comparison": "views/report/comparison.tpl",
  238. }
  239. var pages = map[string]Page{
  240. "report": cachePdf("comparison"),
  241. }
  242. var roles = map[string]int{
  243. "User": 1,
  244. "Manager": 2,
  245. "Admin": 3,
  246. }
  247. var statuses = map[string]int{
  248. "Unsubscribed": 1,
  249. "Trial": 2,
  250. "Free": 3,
  251. "Subscriber": 4,
  252. "Branch": 5,
  253. "Admin": 6,
  254. }
  255. var propertyTypes = []string{
  256. "Single Detached",
  257. "Single Attached",
  258. "Condo Lo-rise",
  259. "Condo Hi-rise",
  260. }
  261. var feeTypes = []string{
  262. "Government",
  263. "Title",
  264. "Required",
  265. "Lender",
  266. "Other",
  267. }
  268. var hookKeys = HookKeys{
  269. InvoicePaid: "",
  270. InvoiceFailed: "",
  271. SubCreated: "",
  272. SubUpdated: "",
  273. SubDeleted: "",
  274. }
  275. var standardPriceId = "price_1OZLK9BPMoXn2pf9kuTAf8rs"
  276. // Used to validate claim in JWT token body. Checks if user id is greater than
  277. // zero and time format is valid
  278. func (c UserClaims) Valid() error {
  279. if c.Id < 1 {
  280. return errors.New("Invalid id")
  281. }
  282. t, err := time.Parse(time.UnixDate, c.Exp)
  283. if err != nil {
  284. return err
  285. }
  286. if t.Before(time.Now()) {
  287. return errors.New("Token expired.")
  288. }
  289. return err
  290. }
  291. func (c VerificationClaims) Valid() error {
  292. if c.Id < 1 {
  293. return errors.New("Invalid id")
  294. }
  295. t, err := time.Parse(time.UnixDate, c.Exp)
  296. if err != nil {
  297. return err
  298. }
  299. if t.Before(time.Now()) {
  300. return errors.New("Token expired.")
  301. }
  302. return err
  303. }
  304. func cachePdf(name string) Page {
  305. // Money is stored in cents, so it must be converted to dollars in reports
  306. dollars := func(cents int) string {
  307. return humanize.Commaf(float64(cents) / 100)
  308. }
  309. // For calculating down payments
  310. diff := func(a, b int) string {
  311. return humanize.Commaf(float64(b-a) / 100)
  312. }
  313. sortFees := func(ftype string, fees []Fee) []Fee {
  314. result := make([]Fee, 0)
  315. for i := range fees {
  316. if fees[i].Type != ftype {
  317. continue
  318. }
  319. result = append(result, fees[i])
  320. }
  321. return result
  322. }
  323. fm := template.FuncMap{
  324. "dollars": dollars,
  325. "diff": diff,
  326. "sortFees": sortFees}
  327. var p = []string{"views/report/master.tpl",
  328. "views/report/header.tpl",
  329. "views/report/summary.tpl",
  330. "views/report/comparison.tpl"}
  331. tpl := template.Must(template.New("master.tpl").Funcs(fm).ParseFiles(p...))
  332. return Page{tpl: tpl, Title: "", Name: name}
  333. }
  334. func (page Page) Render(w http.ResponseWriter) {
  335. err := page.tpl.Execute(w, page)
  336. if err != nil {
  337. log.Print(err)
  338. }
  339. }
  340. func match(path, pattern string, args *[]string) bool {
  341. relock.Lock()
  342. defer relock.Unlock()
  343. regex := regexen[pattern]
  344. if regex == nil {
  345. regex = regexp.MustCompile("^" + pattern + "$")
  346. regexen[pattern] = regex
  347. }
  348. matches := regex.FindStringSubmatch(path)
  349. if len(matches) <= 0 {
  350. return false
  351. }
  352. *args = matches[1:]
  353. return true
  354. }
  355. func (estimate *Estimate) makeResults() []Result {
  356. var results []Result
  357. amortize := func(principle float64, rate float64, periods float64) int {
  358. exp := math.Pow(1+rate, periods)
  359. return int(principle * rate * exp / (exp - 1))
  360. }
  361. for i := range estimate.Loans {
  362. var loan = &estimate.Loans[i]
  363. var result Result = Result{}
  364. // Monthly payments use amortized loan payment formula plus monthly MI,
  365. // plus all other recurring fees
  366. result.LoanPayment = amortize(float64(loan.Amount),
  367. float64(loan.Interest/100/12),
  368. float64(loan.Term*12))
  369. result.TotalMonthly = result.LoanPayment + loan.Hoi + loan.Tax + loan.Hazard
  370. if loan.Mi.Monthly {
  371. result.TotalMonthly = result.TotalMonthly +
  372. int(loan.Mi.Rate/100/12*float32(loan.Amount))
  373. } else {
  374. loan.Mi.Upfront = int(loan.Mi.Rate / 100 * float32(loan.Amount))
  375. }
  376. for i := range loan.Fees {
  377. if loan.Fees[i].Amount > 0 {
  378. result.TotalFees = result.TotalFees + loan.Fees[i].Amount
  379. } else {
  380. result.TotalCredits = result.TotalCredits + loan.Fees[i].Amount
  381. }
  382. }
  383. result.CashToClose =
  384. result.TotalFees + result.TotalCredits + (estimate.Price - loan.Amount)
  385. result.LoanId = loan.Id
  386. loan.Result = result
  387. results = append(results, result)
  388. }
  389. return results
  390. }
  391. func summarize(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  392. var estimate Estimate
  393. err := json.NewDecoder(r.Body).Decode(&estimate)
  394. if err != nil {
  395. http.Error(w, "Invalid estimate.", 422)
  396. return
  397. }
  398. estimate.makeResults()
  399. json.NewEncoder(w).Encode(estimate)
  400. }
  401. func getLoanType(db *sql.DB, id int) (LoanType, error) {
  402. types, err := getLoanTypes(db, id, 0, 0)
  403. if err != nil {
  404. return LoanType{Id: id}, err
  405. }
  406. if len(types) == 0 {
  407. return LoanType{Id: id}, errors.New("No type with that id")
  408. }
  409. return types[0], nil
  410. }
  411. func getLoanTypes(db *sql.DB, id int, user int, branch int) (
  412. []LoanType, error) {
  413. var loans []LoanType
  414. var query = `SELECT
  415. id,
  416. coalesce(user_id, 0),
  417. coalesce(branch_id, 0),
  418. name
  419. FROM loan_type WHERE loan_type.id = CASE @e := ? WHEN 0 THEN id ELSE @e END
  420. OR
  421. loan_type.user_id = CASE @e := ? WHEN 0 THEN id ELSE @e END
  422. OR
  423. loan_type.branch_id = CASE @e := ? WHEN 0 THEN id ELSE @e END`
  424. // Should be changed to specify user
  425. rows, err := db.Query(query, id, user, branch)
  426. if err != nil {
  427. return nil, fmt.Errorf("loan_type error: %v", err)
  428. }
  429. defer rows.Close()
  430. for rows.Next() {
  431. var loan LoanType
  432. if err := rows.Scan(
  433. &loan.Id,
  434. &loan.User,
  435. &loan.Branch,
  436. &loan.Name); err != nil {
  437. log.Printf("Error occured fetching loan: %v", err)
  438. return nil, fmt.Errorf("Error occured fetching loan: %v", err)
  439. }
  440. loans = append(loans, loan)
  441. }
  442. return loans, nil
  443. }
  444. func getFees(db *sql.DB, loan int) ([]Fee, error) {
  445. var fees []Fee
  446. query := `SELECT id, loan_id, amount, perc, type, notes, name, category
  447. FROM fee
  448. WHERE loan_id = ?`
  449. rows, err := db.Query(query, loan)
  450. if err != nil {
  451. return nil, fmt.Errorf("Fee query error %v", err)
  452. }
  453. defer rows.Close()
  454. for rows.Next() {
  455. var fee Fee
  456. if err := rows.Scan(
  457. &fee.Id,
  458. &fee.LoanId,
  459. &fee.Amount,
  460. &fee.Perc,
  461. &fee.Type,
  462. &fee.Notes,
  463. &fee.Name,
  464. &fee.Category,
  465. ); err != nil {
  466. return nil, fmt.Errorf("Fees scanning error: %v", err)
  467. }
  468. fees = append(fees, fee)
  469. }
  470. return fees, nil
  471. }
  472. func fetchFeesTemp(db *sql.DB, user int, branch int) ([]FeeTemplate, error) {
  473. var fees []FeeTemplate
  474. query := `SELECT
  475. id, user_id, COALESCE(branch_id, 0), amount, perc, type, notes, name,
  476. category, auto
  477. FROM fee_template
  478. WHERE user_id = ? OR branch_id = ?
  479. `
  480. rows, err := db.Query(query, user, branch)
  481. if err != nil {
  482. return nil, fmt.Errorf("Fee template query error %v", err)
  483. }
  484. defer rows.Close()
  485. for rows.Next() {
  486. var fee FeeTemplate
  487. if err := rows.Scan(
  488. &fee.Id,
  489. &fee.User,
  490. &fee.Branch,
  491. &fee.Amount,
  492. &fee.Perc,
  493. &fee.Type,
  494. &fee.Notes,
  495. &fee.Name,
  496. &fee.Category,
  497. &fee.Auto); err != nil {
  498. return nil, fmt.Errorf("FeesTemplate scanning error: %v", err)
  499. }
  500. fees = append(fees, fee)
  501. }
  502. return fees, nil
  503. }
  504. func constructEvent(r *http.Request, key string) (*stripe.Event, error) {
  505. b, err := io.ReadAll(r.Body)
  506. if err != nil {
  507. log.Printf("io.ReadAll: %v", err)
  508. return nil, err
  509. }
  510. event, err :=
  511. webhook.ConstructEvent(b, r.Header.Get("Stripe-Signature"), key)
  512. if err != nil {
  513. log.Printf("webhook.ConstructEvent: %v", err)
  514. return nil, err
  515. }
  516. return &event, nil
  517. }
  518. // Fetch fees from the database
  519. func getFeesTemp(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  520. var fees []FeeTemplate
  521. claims, err := getClaims(r)
  522. if err != nil {
  523. w.WriteHeader(500)
  524. return
  525. }
  526. user, err := queryUser(db, claims.Id)
  527. if err != nil {
  528. w.WriteHeader(422)
  529. return
  530. }
  531. fees, err = fetchFeesTemp(db, claims.Id, user.Branch.Id)
  532. json.NewEncoder(w).Encode(fees)
  533. }
  534. // Fetch fees from the database
  535. func createFeesTemp(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  536. var fee FeeTemplate
  537. var query string
  538. var row *sql.Row
  539. var err error
  540. claims, err := getClaims(r)
  541. // var id int // Inserted estimate's id
  542. err = json.NewDecoder(r.Body).Decode(&fee)
  543. if err != nil {
  544. w.WriteHeader(422)
  545. return
  546. }
  547. query = `INSERT INTO fee_template
  548. (
  549. user_id,
  550. branch_id,
  551. amount,
  552. perc,
  553. type,
  554. notes,
  555. name,
  556. auto
  557. )
  558. VALUES (?, NULL, ?, ?, ?, ?, ?, ?)
  559. RETURNING id
  560. `
  561. row = db.QueryRow(query,
  562. claims.Id,
  563. fee.Amount,
  564. fee.Perc,
  565. fee.Type,
  566. fee.Notes,
  567. fee.Name,
  568. fee.Auto,
  569. )
  570. err = row.Scan(&fee.Id)
  571. if err != nil {
  572. w.WriteHeader(500)
  573. return
  574. }
  575. json.NewEncoder(w).Encode(fee)
  576. }
  577. // Fetch fees from the database
  578. func deleteFeeTemp(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  579. var fee FeeTemplate
  580. var query string
  581. var err error
  582. // claims, err := getClaims(r)
  583. // var id int // Inserted estimate's id
  584. err = json.NewDecoder(r.Body).Decode(&fee)
  585. if err != nil {
  586. w.WriteHeader(422)
  587. return
  588. }
  589. query = `DELETE FROM fee_template WHERE id = ?`
  590. _, err = db.Exec(query, fee.Id)
  591. if err != nil {
  592. w.WriteHeader(500)
  593. return
  594. }
  595. }
  596. func deleteEstimate(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  597. var estimate Estimate
  598. var err error
  599. err = json.NewDecoder(r.Body).Decode(&estimate)
  600. if err != nil {
  601. w.WriteHeader(422)
  602. return
  603. }
  604. claims, err := getClaims(r)
  605. err = estimate.del(db, claims.Id)
  606. if err != nil {
  607. http.Error(w, err.Error(), 500)
  608. return
  609. }
  610. }
  611. func deleteET(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  612. var et ETemplate
  613. var err error
  614. err = json.NewDecoder(r.Body).Decode(&et)
  615. if err != nil {
  616. w.WriteHeader(422)
  617. return
  618. }
  619. claims, err := getClaims(r)
  620. err = et.del(db, claims.Id)
  621. if err != nil {
  622. http.Error(w, err.Error(), 500)
  623. return
  624. }
  625. }
  626. func getMi(db *sql.DB, loan int) (MI, error) {
  627. var mi MI
  628. query := `SELECT
  629. type, label, lender, rate, premium, upfront, five_year_total,
  630. initial_premium, initial_rate, initial_amount
  631. FROM mi WHERE loan_id = ?`
  632. rows, err := db.Query(query, loan)
  633. if err != nil {
  634. return mi, err
  635. }
  636. defer rows.Close()
  637. if !rows.Next() {
  638. return mi, nil
  639. }
  640. if err := rows.Scan(
  641. &mi.Type,
  642. &mi.Label,
  643. &mi.Lender,
  644. &mi.Rate,
  645. &mi.Premium,
  646. &mi.Upfront,
  647. &mi.FiveYearTotal,
  648. &mi.InitialAllInPremium,
  649. &mi.InitialAllInRate,
  650. &mi.InitialAmount,
  651. ); err != nil {
  652. return mi, err
  653. }
  654. return mi, nil
  655. }
  656. func (estimate *Estimate) getBorrower(db *sql.DB) error {
  657. query := `SELECT id, credit_score, monthly_income, num FROM borrower
  658. WHERE estimate_id = ? LIMIT 1`
  659. row := db.QueryRow(query, estimate.Id)
  660. if err := row.Scan(
  661. &estimate.Borrower.Id,
  662. &estimate.Borrower.Credit,
  663. &estimate.Borrower.Income,
  664. &estimate.Borrower.Num,
  665. ); err != nil {
  666. return fmt.Errorf("Borrower scanning error: %v", err)
  667. }
  668. return nil
  669. }
  670. // Query Lender APIs and parse responses into MI structs
  671. func fetchMi(db *sql.DB, estimate *Estimate, pos int) []MI {
  672. var loan Loan = estimate.Loans[pos]
  673. var ltv = func(l float32) string {
  674. switch {
  675. case l > 95:
  676. return "LTV97"
  677. case l > 90:
  678. return "LTV95"
  679. case l > 85:
  680. return "LTV90"
  681. default:
  682. return "LTV85"
  683. }
  684. }
  685. var term = func(t int) string {
  686. switch {
  687. case t <= 10:
  688. return "A10"
  689. case t <= 15:
  690. return "A15"
  691. case t <= 20:
  692. return "A20"
  693. case t <= 25:
  694. return "A25"
  695. case t <= 30:
  696. return "A30"
  697. default:
  698. return "A40"
  699. }
  700. }
  701. var propertyCodes = map[string]string{
  702. "Single Attached": "SFO",
  703. "Single Detached": "SFO",
  704. "Condo Lo-rise": "CON",
  705. "Condo Hi-rise": "CON",
  706. }
  707. var purposeCodes = map[string]string{
  708. "Purchase": "PUR",
  709. "Refinance": "RRT",
  710. }
  711. body, err := json.Marshal(map[string]any{
  712. "zipCode": estimate.Zip,
  713. "stateCode": "CA",
  714. "address": "",
  715. "propertyTypeCode": propertyCodes[estimate.Property],
  716. "occupancyTypeCode": "PRS",
  717. "loanPurposeCode": purposeCodes[estimate.Transaction],
  718. "loanAmount": loan.Amount,
  719. "loanToValue": ltv(loan.Ltv),
  720. "amortizationTerm": term(loan.Term),
  721. "loanTypeCode": "FXD",
  722. "duLpDecisionCode": "DAE",
  723. "loanProgramCodes": []any{},
  724. "debtToIncome": loan.Dti,
  725. "wholesaleLoan": 0,
  726. "coveragePercentageCode": "L30",
  727. "productCode": "BPM",
  728. "renewalTypeCode": "CON",
  729. "numberOfBorrowers": 1,
  730. "coBorrowerCreditScores": []any{},
  731. "borrowerCreditScore": strconv.Itoa(estimate.Borrower.Credit),
  732. "masterPolicy": nil,
  733. "selfEmployedIndicator": false,
  734. "armType": "",
  735. "userId": 44504,
  736. })
  737. /*
  738. if err != nil {
  739. log.Printf("Could not marshal NationalMI body: \n%v\n%v\n",
  740. bytes.NewBuffer(body), err)
  741. func queryAddress(db *sql.DB, id int) ( Address, error ) {
  742. var address Address = Address{Id: id}
  743. var err error
  744. row := db.QueryRow(
  745. `SELECT id, full_address, street, city, region, country, zip
  746. FROM address WHERE id = ?`, id)
  747. err = row.Scan(
  748. &address.Id,
  749. &address.Full,
  750. &address.Street,
  751. &address.City,
  752. &address.Region,
  753. &address.Country,
  754. &address.Zip,
  755. )
  756. return address, err
  757. }
  758. }
  759. */
  760. req, err := http.NewRequest("POST",
  761. "https://rate-gps.nationalmi.com/rates/productRateQuote",
  762. bytes.NewBuffer(body))
  763. req.Header.Add("Content-Type", "application/json")
  764. req.AddCookie(&http.Cookie{
  765. Name: "nmirategps_email",
  766. Value: os.Getenv("NationalMIEmail")})
  767. resp, err := http.DefaultClient.Do(req)
  768. var res map[string]interface{}
  769. var result []MI
  770. if resp.StatusCode != 200 {
  771. log.Printf("the status: %v\nthe resp: %v\n the req: %v\n the body: %v\n",
  772. resp.Status, resp, req.Body, bytes.NewBuffer(body))
  773. } else {
  774. json.NewDecoder(resp.Body).Decode(&res)
  775. // estimate.Loans[pos].Mi = res
  776. // Parse res into result here
  777. }
  778. log.Println(err)
  779. return result
  780. }
  781. // Make comparison PDF
  782. func generatePDF(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  783. }
  784. func login(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  785. var id int
  786. var role string
  787. var err error
  788. var user User
  789. json.NewDecoder(r.Body).Decode(&user)
  790. row := db.QueryRow(
  791. `SELECT id, role FROM user WHERE email = ? AND password = sha2(?, 256)`,
  792. user.Email, user.Password,
  793. )
  794. err = row.Scan(&id, &role)
  795. if err != nil {
  796. http.Error(w, "Invalid Credentials.", http.StatusUnauthorized)
  797. return
  798. }
  799. err = setTokenCookie(id, role, w)
  800. if err != nil {
  801. http.Error(w, err.Error(), 500)
  802. }
  803. }
  804. func setTokenCookie(id int, role string, w http.ResponseWriter) error {
  805. token := jwt.NewWithClaims(jwt.SigningMethodHS256,
  806. UserClaims{Id: id, Role: role,
  807. Exp: time.Now().Add(time.Minute * 30).Format(time.UnixDate)})
  808. tokenStr, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
  809. if err != nil {
  810. log.Println("Token could not be signed: ", err, tokenStr)
  811. return err
  812. }
  813. cookie := http.Cookie{Name: "skouter",
  814. Value: tokenStr,
  815. Path: "/",
  816. Expires: time.Now().Add(time.Hour * 1)}
  817. http.SetCookie(w, &cookie)
  818. return nil
  819. }
  820. func removeTokenCookie(w http.ResponseWriter) {
  821. cookie := http.Cookie{Name: "skouter",
  822. Value: "",
  823. Path: "/",
  824. Expires: time.Unix(0, 0)}
  825. http.SetCookie(w, &cookie)
  826. return
  827. }
  828. func refreshToken(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  829. claims, _ := getClaims(r)
  830. if claims.Valid() != nil {
  831. removeTokenCookie(w)
  832. return
  833. }
  834. err := setTokenCookie(claims.Id, claims.Role, w)
  835. if err != nil {
  836. http.Error(w,
  837. "Token generation error",
  838. http.StatusInternalServerError)
  839. }
  840. return
  841. }
  842. // Checks both Authorization header and cookie for bearer token and
  843. // Gives priority to the header.
  844. func getClaims(r *http.Request) (UserClaims, error) {
  845. claims := new(UserClaims)
  846. _, tokenStr, found := strings.Cut(r.Header.Get("Authorization"), " ")
  847. c, err := r.Cookie("skouter")
  848. if !found && err != nil {
  849. return *claims, errors.New("Token not found")
  850. }
  851. if !found {
  852. tokenStr = c.Value
  853. }
  854. // Pull token payload into UserClaims
  855. _, err = jwt.ParseWithClaims(tokenStr, claims,
  856. func(token *jwt.Token) (any, error) {
  857. return []byte(os.Getenv("JWT_SECRET")), nil
  858. })
  859. if err != nil {
  860. return *claims, err
  861. }
  862. if err = claims.Valid(); err != nil {
  863. return *claims, err
  864. }
  865. return *claims, nil
  866. }
  867. func guard(r *http.Request, required int) bool {
  868. claims, err := getClaims(r)
  869. if err != nil {
  870. return false
  871. }
  872. if roles[claims.Role] < required {
  873. return false
  874. }
  875. return true
  876. }
  877. // Inserts an address and returns it's ID along with any errors.
  878. func insertAddress(db *sql.DB, address Address) (int, error) {
  879. var query string
  880. var row *sql.Row
  881. var err error
  882. var id int // Inserted user's id
  883. query = `INSERT INTO address
  884. (
  885. full_address,
  886. street,
  887. city,
  888. region,
  889. country,
  890. zip
  891. )
  892. VALUES (?, ?, ?, ?, ?, ?)
  893. RETURNING id
  894. `
  895. row = db.QueryRow(query,
  896. address.Full,
  897. address.Street,
  898. address.City,
  899. address.Region,
  900. address.Country,
  901. address.Zip,
  902. )
  903. err = row.Scan(&id)
  904. return id, err
  905. }
  906. // Inserts an address and returns it's ID along with any errors.
  907. func insertBranch(db *sql.DB, branch Branch) (int, error) {
  908. var query string
  909. var row *sql.Row
  910. var err error
  911. var id int // Inserted user's id
  912. query = `INSERT INTO branch
  913. (
  914. name,
  915. type,
  916. letterhead,
  917. num,
  918. phone,
  919. address
  920. )
  921. VALUES (?, ?, ?, ?, ?, ?)
  922. RETURNING id
  923. `
  924. row = db.QueryRow(query,
  925. branch.Name,
  926. branch.Type,
  927. branch.Letterhead,
  928. branch.Num,
  929. branch.Phone,
  930. branch.Address.Id,
  931. )
  932. err = row.Scan(&id)
  933. return id, err
  934. }
  935. // Inserts an address and returns it's ID along with any errors.
  936. func insertLicense(db *sql.DB, license License) (int, error) {
  937. var query string
  938. var row *sql.Row
  939. var err error
  940. var id int // Inserted license's id
  941. query = `INSERT INTO license
  942. (
  943. user_id,
  944. type,
  945. num
  946. )
  947. VALUES (?, ?, ?)
  948. RETURNING id
  949. `
  950. row = db.QueryRow(query,
  951. license.UserId,
  952. license.Type,
  953. license.Num,
  954. )
  955. err = row.Scan(&id)
  956. return id, err
  957. }
  958. func queryLicense(db *sql.DB, user int) (License, error) {
  959. var license License = License{UserId: user}
  960. var err error
  961. row := db.QueryRow(
  962. `SELECT id, type, num FROM license WHERE user_id = ?`,
  963. user)
  964. err = row.Scan(
  965. &license.Id,
  966. &license.Type,
  967. &license.Num,
  968. )
  969. return license, err
  970. }
  971. func queryAddress(db *sql.DB, id int) (Address, error) {
  972. var address Address = Address{Id: id}
  973. var err error
  974. row := db.QueryRow(
  975. `SELECT id, full_address, street, city, region, country, zip
  976. FROM address WHERE id = ?`, id)
  977. err = row.Scan(
  978. &address.Id,
  979. &address.Full,
  980. &address.Street,
  981. &address.City,
  982. &address.Region,
  983. &address.Country,
  984. &address.Zip,
  985. )
  986. return address, err
  987. }
  988. func queryBranch(db *sql.DB, id int) (Branch, error) {
  989. var branch Branch = Branch{Id: id}
  990. var err error
  991. row := db.QueryRow(
  992. `SELECT id, name, type, letterhead, num, phone, address
  993. FROM branch WHERE id = ?`, id)
  994. err = row.Scan(
  995. &branch.Id,
  996. &branch.Name,
  997. &branch.Type,
  998. &branch.Letterhead,
  999. &branch.Num,
  1000. &branch.Phone,
  1001. &branch.Address.Id,
  1002. )
  1003. return branch, err
  1004. }
  1005. func queryUser(db *sql.DB, id int) (User, error) {
  1006. var user User
  1007. var query string
  1008. var err error
  1009. query = `SELECT
  1010. u.id,
  1011. u.email,
  1012. u.first_name,
  1013. u.last_name,
  1014. coalesce(u.branch_id, 0),
  1015. u.country,
  1016. u.title,
  1017. coalesce(u.status, ''),
  1018. coalesce(u.customer_id, ''),
  1019. u.verified,
  1020. u.role,
  1021. u.address,
  1022. u.phone
  1023. FROM user u WHERE u.id = ?
  1024. `
  1025. row := db.QueryRow(query, id)
  1026. if err != nil {
  1027. return user, err
  1028. }
  1029. err = row.Scan(
  1030. &user.Id,
  1031. &user.Email,
  1032. &user.FirstName,
  1033. &user.LastName,
  1034. &user.Branch.Id,
  1035. &user.Country,
  1036. &user.Title,
  1037. &user.Status,
  1038. &user.CustomerId,
  1039. &user.Verified,
  1040. &user.Role,
  1041. &user.Address.Id,
  1042. &user.Phone,
  1043. )
  1044. if err != nil {
  1045. return user, err
  1046. }
  1047. user.Address, err = queryAddress(db, user.Address.Id)
  1048. if err != nil {
  1049. return user, err
  1050. }
  1051. if user.Branch.Id > 0 {
  1052. user.Branch, err = queryBranch(db, user.Branch.Id)
  1053. if err != nil {
  1054. return user, err
  1055. }
  1056. }
  1057. return user, nil
  1058. }
  1059. func queryCustomer(db *sql.DB, id string) (User, error) {
  1060. var user User
  1061. var query string
  1062. var err error
  1063. query = `SELECT
  1064. u.id,
  1065. u.email,
  1066. u.first_name,
  1067. u.last_name,
  1068. coalesce(u.branch_id, 0),
  1069. u.country,
  1070. u.title,
  1071. coalesce(u.status, ''),
  1072. coalesce(u.customer_id, ''),
  1073. u.verified,
  1074. u.role,
  1075. u.address,
  1076. u.phone
  1077. FROM user u WHERE u.customer_id = ?
  1078. `
  1079. row := db.QueryRow(query, id)
  1080. if err != nil {
  1081. return user, err
  1082. }
  1083. err = row.Scan(
  1084. &user.Id,
  1085. &user.Email,
  1086. &user.FirstName,
  1087. &user.LastName,
  1088. &user.Branch.Id,
  1089. &user.Country,
  1090. &user.Title,
  1091. &user.Status,
  1092. &user.CustomerId,
  1093. &user.Verified,
  1094. &user.Role,
  1095. &user.Address.Id,
  1096. &user.Phone,
  1097. )
  1098. if err != nil {
  1099. return user, err
  1100. }
  1101. user.Address, err = queryAddress(db, user.Address.Id)
  1102. if err != nil {
  1103. return user, err
  1104. }
  1105. user.Branch, err = queryBranch(db, user.Branch.Id)
  1106. if err != nil {
  1107. return user, err
  1108. }
  1109. return user, nil
  1110. }
  1111. // Can probably be deleted.
  1112. func queryUsers(db *sql.DB, id int) ([]User, error) {
  1113. var users []User
  1114. var query string
  1115. var rows *sql.Rows
  1116. var err error
  1117. query = `SELECT
  1118. u.id,
  1119. u.email,
  1120. u.first_name,
  1121. u.last_name,
  1122. coalesce(u.branch_id, 0),
  1123. u.country,
  1124. u.title,
  1125. coalesce(u.status, ''),
  1126. u.verified,
  1127. u.role,
  1128. u.address,
  1129. u.phone
  1130. FROM user u WHERE u.id = CASE @e := ? WHEN 0 THEN u.id ELSE @e END
  1131. `
  1132. rows, err = db.Query(query, id)
  1133. if err != nil {
  1134. return users, err
  1135. }
  1136. defer rows.Close()
  1137. for rows.Next() {
  1138. var user User
  1139. if err := rows.Scan(
  1140. &user.Id,
  1141. &user.Email,
  1142. &user.FirstName,
  1143. &user.LastName,
  1144. &user.Branch.Id,
  1145. &user.Country,
  1146. &user.Title,
  1147. &user.Status,
  1148. &user.Verified,
  1149. &user.Role,
  1150. &user.Address.Id,
  1151. &user.Phone,
  1152. ); err != nil {
  1153. return users, err
  1154. }
  1155. user.Address, err = queryAddress(db, user.Address.Id)
  1156. if err != nil {
  1157. return users, err
  1158. }
  1159. user.Branch, err = queryBranch(db, user.Branch.Id)
  1160. if err != nil {
  1161. return users, err
  1162. }
  1163. users = append(users, user)
  1164. }
  1165. // Prevents runtime panics
  1166. if len(users) == 0 {
  1167. return users, errors.New("User not found.")
  1168. }
  1169. return users, nil
  1170. }
  1171. func querySub(db *sql.DB, id int) (Subscription, error) {
  1172. var query string
  1173. var err error
  1174. var s Subscription
  1175. query = `SELECT
  1176. id,
  1177. stripe_id,
  1178. user_id,
  1179. customer_id,
  1180. current_period_end,
  1181. current_period_start,
  1182. client_secret,
  1183. payment_status
  1184. FROM subscription WHERE id = ?
  1185. `
  1186. row := db.QueryRow(query, id)
  1187. err = row.Scan(
  1188. &s.Id,
  1189. &s.StripeId,
  1190. &s.CustomerId,
  1191. &s.End,
  1192. &s.Start,
  1193. &s.ClientSecret,
  1194. &s.PaymentStatus,
  1195. )
  1196. return s, err
  1197. }
  1198. func (user *User) querySub(db *sql.DB) error {
  1199. var query string
  1200. var err error
  1201. query = `SELECT
  1202. id,
  1203. stripe_id,
  1204. user_id,
  1205. customer_id,
  1206. price_id,
  1207. current_period_end,
  1208. current_period_start,
  1209. client_secret,
  1210. payment_status
  1211. FROM subscription WHERE user_id = ?
  1212. `
  1213. row := db.QueryRow(query, user.Id)
  1214. err = row.Scan(
  1215. &user.Sub.Id,
  1216. &user.Sub.StripeId,
  1217. &user.Sub.UserId,
  1218. &user.Sub.CustomerId,
  1219. &user.Sub.PriceId,
  1220. &user.Sub.End,
  1221. &user.Sub.Start,
  1222. &user.Sub.ClientSecret,
  1223. &user.Sub.PaymentStatus,
  1224. )
  1225. return err
  1226. }
  1227. func (estimate *Estimate) insertResults(db *sql.DB) error {
  1228. var query string
  1229. var row *sql.Row
  1230. var err error
  1231. var id int
  1232. query = `INSERT INTO estimate_result
  1233. (
  1234. loan_id,
  1235. loan_payment,
  1236. total_monthly,
  1237. total_fees,
  1238. total_credits,
  1239. cash_to_close
  1240. )
  1241. VALUES (?, ?, ?, ?, ?, ?)
  1242. RETURNING id
  1243. `
  1244. for i := range estimate.Loans {
  1245. r := estimate.Loans[i].Result
  1246. r.LoanId = estimate.Loans[i].Id
  1247. row = db.QueryRow(query,
  1248. r.LoanId,
  1249. r.LoanPayment,
  1250. r.TotalMonthly,
  1251. r.TotalFees,
  1252. r.TotalCredits,
  1253. r.CashToClose,
  1254. )
  1255. err = row.Scan(&id)
  1256. if err != nil {
  1257. return err
  1258. }
  1259. r.Id = id
  1260. }
  1261. return nil
  1262. }
  1263. // Insert user returning it's ID or any error
  1264. func insertUser(db *sql.DB, user User) (int, error) {
  1265. var query string
  1266. var row *sql.Row
  1267. var err error
  1268. var id int // Inserted user's id
  1269. user.Address.Id, err = insertAddress(db, user.Address)
  1270. if err != nil {
  1271. return 0, err
  1272. }
  1273. query = `INSERT INTO user
  1274. (
  1275. email,
  1276. first_name,
  1277. last_name,
  1278. password,
  1279. role,
  1280. title,
  1281. status,
  1282. verified,
  1283. address,
  1284. country,
  1285. branch_id,
  1286. phone,
  1287. created,
  1288. last_login
  1289. )
  1290. VALUES (?, ?, ?, sha2(?, 256), ?, ?, ?, ?, ?, ?,
  1291. CASE @b := ? WHEN 0 THEN NULL ELSE @b END,
  1292. ?, NOW(), NOW())
  1293. RETURNING id
  1294. `
  1295. row = db.QueryRow(query,
  1296. user.Email,
  1297. user.FirstName,
  1298. user.LastName,
  1299. user.Password,
  1300. user.Role,
  1301. user.Title,
  1302. user.Status,
  1303. user.Verified,
  1304. user.Address.Id,
  1305. user.Country,
  1306. user.Branch.Id,
  1307. user.Phone,
  1308. )
  1309. err = row.Scan(&id)
  1310. if err != nil {
  1311. return 0, err
  1312. }
  1313. user.Id = id
  1314. return id, nil
  1315. }
  1316. // Insert user returning it's ID or any error
  1317. func (sub *Subscription) insertSub(db *sql.DB) (error) {
  1318. var query string
  1319. var row *sql.Row
  1320. var err error
  1321. query = `INSERT INTO subscription
  1322. (
  1323. stripe_id,
  1324. user_id,
  1325. customer_id,
  1326. price_id,
  1327. current_period_end,
  1328. current_period_start,
  1329. client_secret,
  1330. payment_status,
  1331. status
  1332. )
  1333. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  1334. RETURNING id
  1335. `
  1336. row = db.QueryRow(query,
  1337. sub.StripeId,
  1338. sub.UserId,
  1339. sub.CustomerId,
  1340. sub.PriceId,
  1341. sub.End,
  1342. sub.Start,
  1343. sub.ClientSecret,
  1344. sub.PaymentStatus,
  1345. sub.Status,
  1346. )
  1347. err = row.Scan(&sub.Id)
  1348. return err
  1349. }
  1350. func (sub *Subscription) updateSub(db *sql.DB) error {
  1351. var query string
  1352. var err error
  1353. query = `UPDATE subscription
  1354. SET client_secret = CASE @a := ? WHEN '' THEN client_secret ELSE @a END,
  1355. current_period_end = CASE
  1356. @b := ? WHEN 0 THEN current_period_end ELSE @b END,
  1357. current_period_start = CASE
  1358. @c := ? WHEN 0 THEN current_period_start ELSE @c END,
  1359. payment_status = CASE @d := ? WHEN '' THEN client_secret ELSE @d END,
  1360. status = CASE @e := ? WHEN '' THEN client_secret ELSE @e END
  1361. WHERE id = ?
  1362. `
  1363. _, err = db.Exec(query,
  1364. sub.ClientSecret,
  1365. sub.End,
  1366. sub.Start,
  1367. sub.PaymentStatus,
  1368. sub.Status,
  1369. sub.Id,
  1370. )
  1371. if err != nil { return err }
  1372. return err
  1373. }
  1374. // Updates a user's stripe customer ID.
  1375. func (user *User) updateCustomerId(db *sql.DB, cid string) (error) {
  1376. var query string
  1377. var err error
  1378. query = `UPDATE user SET
  1379. customer_id = ?
  1380. WHERE id = ?
  1381. `
  1382. _, err = db.Exec(query,
  1383. cid,
  1384. user.Id,
  1385. )
  1386. if err != nil { return err }
  1387. user.CustomerId = cid
  1388. return nil
  1389. }
  1390. func updateAddress(address Address, db *sql.DB) error {
  1391. query := `
  1392. UPDATE address
  1393. SET
  1394. full_address = CASE @e := ? WHEN '' THEN full_address ELSE @e END,
  1395. street = CASE @fn := ? WHEN '' THEN street ELSE @fn END,
  1396. city = CASE @ln := ? WHEN '' THEN city ELSE @ln END,
  1397. region = CASE @r := ? WHEN '' THEN region ELSE @r END,
  1398. country = CASE @r := ? WHEN '' THEN country ELSE @r END,
  1399. zip = CASE @r := ? WHEN '' THEN zip ELSE @r END
  1400. WHERE id = ?
  1401. `
  1402. _, err := db.Exec(query,
  1403. address.Full,
  1404. address.Street,
  1405. address.City,
  1406. address.Region,
  1407. address.Country,
  1408. address.Zip,
  1409. address.Id,
  1410. )
  1411. return err
  1412. }
  1413. func (user *User) update(db *sql.DB) error {
  1414. query := `
  1415. UPDATE user
  1416. SET
  1417. email = CASE @e := ? WHEN '' THEN email ELSE @e END,
  1418. first_name = CASE @fn := ? WHEN '' THEN first_name ELSE @fn END,
  1419. last_name = CASE @ln := ? WHEN '' THEN last_name ELSE @ln END,
  1420. role = CASE @r := ? WHEN '' THEN role ELSE @r END,
  1421. password = CASE @p := ? WHEN '' THEN password ELSE sha2(@p, 256) END
  1422. WHERE id = ?
  1423. `
  1424. _, err := db.Exec(query,
  1425. user.Email,
  1426. user.FirstName,
  1427. user.LastName,
  1428. user.Role,
  1429. user.Password,
  1430. user.Id,
  1431. )
  1432. return err
  1433. }
  1434. func getUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1435. claims, err := getClaims(r)
  1436. if err != nil {
  1437. w.WriteHeader(500)
  1438. return
  1439. }
  1440. user, err := queryUser(db, claims.Id)
  1441. if err != nil {
  1442. w.WriteHeader(422)
  1443. log.Println(err)
  1444. return
  1445. }
  1446. json.NewEncoder(w).Encode(user)
  1447. }
  1448. func getUsers(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1449. users, err := queryUsers(db, 0)
  1450. if err != nil {
  1451. w.WriteHeader(http.StatusInternalServerError)
  1452. return
  1453. }
  1454. json.NewEncoder(w).Encode(users)
  1455. }
  1456. // Updates a user using only specified values in the JSON body
  1457. func setUser(user User, db *sql.DB) error {
  1458. _, err := mail.ParseAddress(user.Email)
  1459. if err != nil {
  1460. return err
  1461. }
  1462. if roles[user.Role] == 0 {
  1463. return errors.New("Invalid role")
  1464. }
  1465. err = user.update(db)
  1466. if err != nil {
  1467. return err
  1468. }
  1469. err = updateAddress(user.Address, db)
  1470. if err != nil {
  1471. return err
  1472. }
  1473. return nil
  1474. }
  1475. func patchUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1476. var user User
  1477. err := json.NewDecoder(r.Body).Decode(&user)
  1478. if err != nil {
  1479. http.Error(w, "Invalid fields", 422)
  1480. return
  1481. }
  1482. err = setUser(user, db)
  1483. if err != nil {
  1484. http.Error(w, err.Error(), 422)
  1485. return
  1486. }
  1487. }
  1488. // Update specified fields of the user specified in the claim
  1489. func patchSelf(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1490. claim, err := getClaims(r)
  1491. var user User
  1492. json.NewDecoder(r.Body).Decode(&user)
  1493. // First check that the target user to be updated is the same as the claim id, and
  1494. // their role is unchanged.
  1495. if err != nil || claim.Id != user.Id {
  1496. http.Error(w, "Target user's id does not match claim.", 401)
  1497. return
  1498. }
  1499. if claim.Role != user.Role && user.Role != "" {
  1500. http.Error(w, "Administrator required to escalate role.", 401)
  1501. return
  1502. }
  1503. err = setUser(user, db)
  1504. if err != nil {
  1505. http.Error(w, err.Error(), 422)
  1506. return
  1507. }
  1508. }
  1509. func deleteUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1510. var user User
  1511. err := json.NewDecoder(r.Body).Decode(&user)
  1512. if err != nil {
  1513. http.Error(w, "Invalid fields.", 422)
  1514. return
  1515. }
  1516. query := `DELETE FROM user WHERE id = ?`
  1517. _, err = db.Exec(query, user.Id)
  1518. if err != nil {
  1519. http.Error(w, "Could not delete.", 500)
  1520. }
  1521. }
  1522. // Checks if a user's entries are reasonable before database insertion.
  1523. // This function is very important because it is the only thing preventing
  1524. // anyone from creating an admin user. These error messages are displayed to
  1525. // the user.
  1526. func (user *User) validate() error {
  1527. _, err := mail.ParseAddress(user.Email)
  1528. if err != nil {
  1529. return errors.New("Invalid email.")
  1530. }
  1531. if roles[user.Role] == 0 {
  1532. return errors.New("Invalid role.")
  1533. }
  1534. if roles[user.Role] == roles["Admin"] {
  1535. return errors.New("New user cannot be an Admin.")
  1536. }
  1537. if user.FirstName == "" {
  1538. return errors.New("Given name cannot be empty.")
  1539. }
  1540. if user.LastName == "" {
  1541. return errors.New("Surname cannot be empty.")
  1542. }
  1543. if user.Password == "" {
  1544. return errors.New("Empty password")
  1545. }
  1546. return nil
  1547. }
  1548. func createUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1549. var user User
  1550. err := json.NewDecoder(r.Body).Decode(&user)
  1551. if err != nil {
  1552. http.Error(w, "Invalid fields.", 422)
  1553. return
  1554. }
  1555. user.Role = "User"
  1556. user.Status = "Trial"
  1557. err = user.validate()
  1558. if err != nil {
  1559. http.Error(w, err.Error(), 422)
  1560. return
  1561. }
  1562. user.Id, err = insertUser(db, user)
  1563. if err != nil {
  1564. http.Error(w, err.Error(), 422)
  1565. return
  1566. }
  1567. err = setTokenCookie(user.Id, user.Role, w)
  1568. if err != nil {
  1569. http.Error(w, err.Error(), 500)
  1570. return
  1571. }
  1572. json.NewEncoder(w).Encode(user)
  1573. user.sendVerificationEmail()
  1574. }
  1575. func checkPassword(db *sql.DB, id int, pass string) bool {
  1576. var p string
  1577. query := `SELECT
  1578. password
  1579. FROM user WHERE user.id = ? AND password = sha2(?, 256)
  1580. `
  1581. row := db.QueryRow(query, id, pass)
  1582. err := row.Scan(&p)
  1583. if err != nil {
  1584. return false
  1585. }
  1586. return true
  1587. }
  1588. func setPassword(db *sql.DB, id int, pass string) error {
  1589. query := `UPDATE user
  1590. SET password = sha2(?, 256)
  1591. WHERE user.id = ?
  1592. `
  1593. _, err := db.Exec(query, pass, id)
  1594. if err != nil {
  1595. return errors.New("Could not insert password.")
  1596. }
  1597. return nil
  1598. }
  1599. func changePassword(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1600. var pass Password
  1601. claim, err := getClaims(r)
  1602. err = json.NewDecoder(r.Body).Decode(&pass)
  1603. if err != nil {
  1604. http.Error(w, "Bad fields.", 422)
  1605. return
  1606. }
  1607. if checkPassword(db, claim.Id, pass.Old) {
  1608. err = setPassword(db, claim.Id, pass.New)
  1609. } else {
  1610. http.Error(w, "Incorrect old password.", 401)
  1611. return
  1612. }
  1613. if err != nil {
  1614. http.Error(w, err.Error(), 500)
  1615. return
  1616. }
  1617. }
  1618. func fetchAvatar(db *sql.DB, user int) ([]byte, error) {
  1619. var img []byte
  1620. var query string
  1621. var err error
  1622. query = `SELECT
  1623. avatar
  1624. FROM user WHERE user.id = ?
  1625. `
  1626. row := db.QueryRow(query, user)
  1627. err = row.Scan(&img)
  1628. if err != nil {
  1629. return img, err
  1630. }
  1631. return img, nil
  1632. }
  1633. func insertAvatar(db *sql.DB, user int, img []byte) error {
  1634. query := `UPDATE user
  1635. SET avatar = ?
  1636. WHERE id = ?
  1637. `
  1638. _, err := db.Exec(query, img, user)
  1639. if err != nil {
  1640. return err
  1641. }
  1642. return nil
  1643. }
  1644. func fetchLetterhead(db *sql.DB, user int) ([]byte, error) {
  1645. var img []byte
  1646. var query string
  1647. var err error
  1648. query = `SELECT
  1649. letterhead
  1650. FROM user WHERE user.id = ?
  1651. `
  1652. row := db.QueryRow(query, user)
  1653. err = row.Scan(&img)
  1654. if err != nil {
  1655. return img, err
  1656. }
  1657. return img, nil
  1658. }
  1659. func insertLetterhead(db *sql.DB, user int, img []byte) error {
  1660. query := `UPDATE user
  1661. SET letterhead = ?
  1662. WHERE id = ?
  1663. `
  1664. _, err := db.Exec(query, img, user)
  1665. if err != nil {
  1666. return err
  1667. }
  1668. return nil
  1669. }
  1670. func setAvatar(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1671. var validTypes []string = []string{"image/png", "image/jpeg"}
  1672. var isValidType bool
  1673. claims, err := getClaims(r)
  1674. if err != nil {
  1675. http.Error(w, "Invalid token.", 422)
  1676. return
  1677. }
  1678. img, err := io.ReadAll(r.Body)
  1679. if err != nil {
  1680. http.Error(w, "Invalid file.", 422)
  1681. return
  1682. }
  1683. for _, v := range validTypes {
  1684. if v == http.DetectContentType(img) {
  1685. isValidType = true
  1686. }
  1687. }
  1688. if !isValidType {
  1689. http.Error(w, "Invalid file type.", 422)
  1690. return
  1691. }
  1692. err = insertAvatar(db, claims.Id, img)
  1693. if err != nil {
  1694. http.Error(w, "Could not insert.", 500)
  1695. return
  1696. }
  1697. }
  1698. func getAvatar(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1699. claims, err := getClaims(r)
  1700. if err != nil {
  1701. http.Error(w, "Invalid token.", 422)
  1702. return
  1703. }
  1704. img, err := fetchAvatar(db, claims.Id)
  1705. if err != nil {
  1706. http.Error(w, "Could not retrieve.", 500)
  1707. return
  1708. }
  1709. w.Header().Set("Content-Type", http.DetectContentType(img))
  1710. w.Write(img)
  1711. }
  1712. func setLetterhead(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1713. var validTypes []string = []string{"image/png", "image/jpeg"}
  1714. var isValidType bool
  1715. claims, err := getClaims(r)
  1716. if err != nil {
  1717. http.Error(w, "Invalid token.", 422)
  1718. return
  1719. }
  1720. img, err := io.ReadAll(r.Body)
  1721. if err != nil {
  1722. http.Error(w, "Invalid file.", 422)
  1723. return
  1724. }
  1725. for _, v := range validTypes {
  1726. if v == http.DetectContentType(img) {
  1727. isValidType = true
  1728. }
  1729. }
  1730. if !isValidType {
  1731. http.Error(w, "Invalid file type.", 422)
  1732. return
  1733. }
  1734. err = insertLetterhead(db, claims.Id, img)
  1735. if err != nil {
  1736. http.Error(w, "Could not insert.", 500)
  1737. return
  1738. }
  1739. }
  1740. func getLetterhead(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  1741. claims, err := getClaims(r)
  1742. if err != nil {
  1743. http.Error(w, "Invalid token.", 422)
  1744. return
  1745. }
  1746. img, err := fetchLetterhead(db, claims.Id)
  1747. if err != nil {
  1748. http.Error(w, "Could not retrieve.", 500)
  1749. return
  1750. }
  1751. w.Header().Set("Content-Type", http.DetectContentType(img))
  1752. w.Write(img)
  1753. }
  1754. func queryBorrower(db *sql.DB, id int) (Borrower, error) {
  1755. var borrower Borrower
  1756. var query string
  1757. var err error
  1758. query = `SELECT
  1759. l.id,
  1760. l.credit_score,
  1761. l.num,
  1762. l.monthly_income
  1763. FROM borrower l WHERE l.id = ?
  1764. `
  1765. row := db.QueryRow(query, id)
  1766. err = row.Scan(
  1767. borrower.Id,
  1768. borrower.Credit,
  1769. borrower.Num,
  1770. borrower.Income,
  1771. )
  1772. if err != nil {
  1773. return borrower, err
  1774. }
  1775. return borrower, nil
  1776. }
  1777. // Must have an estimate ID 'e', but not necessarily a loan id 'id'
  1778. func getResults(db *sql.DB, e int, id int) ([]Result, error) {
  1779. var results []Result
  1780. var query string
  1781. var rows *sql.Rows
  1782. var err error
  1783. query = `SELECT
  1784. r.id,
  1785. loan_id,
  1786. loan_payment,
  1787. total_monthly,
  1788. total_fees,
  1789. total_credits,
  1790. cash_to_close
  1791. FROM estimate_result r
  1792. INNER JOIN loan
  1793. ON r.loan_id = loan.id
  1794. WHERE r.id = CASE @e := ? WHEN 0 THEN r.id ELSE @e END
  1795. AND loan.estimate_id = ?
  1796. `
  1797. rows, err = db.Query(query, id, e)
  1798. if err != nil {
  1799. return results, err
  1800. }
  1801. defer rows.Close()
  1802. for rows.Next() {
  1803. var result Result
  1804. if err := rows.Scan(
  1805. &result.Id,
  1806. &result.LoanId,
  1807. &result.LoanPayment,
  1808. &result.TotalMonthly,
  1809. &result.TotalFees,
  1810. &result.TotalCredits,
  1811. &result.CashToClose,
  1812. ); err != nil {
  1813. return results, err
  1814. }
  1815. results = append(results, result)
  1816. }
  1817. // Prevents runtime panics
  1818. // if len(results) == 0 { return results, errors.New("Result not found.") }
  1819. return results, nil
  1820. }
  1821. // Retrieve an estimate result with a specified loan id
  1822. func getResult(db *sql.DB, loan int) (Result, error) {
  1823. var result Result
  1824. var query string
  1825. var err error
  1826. query = `SELECT
  1827. r.id,
  1828. loan_id,
  1829. loan_payment,
  1830. total_monthly,
  1831. total_fees,
  1832. total_credits,
  1833. cash_to_close
  1834. FROM estimate_result r
  1835. INNER JOIN loan
  1836. ON r.loan_id = loan.id
  1837. WHERE loan.Id = ?
  1838. `
  1839. row := db.QueryRow(query, loan)
  1840. err = row.Scan(
  1841. &result.Id,
  1842. &result.LoanId,
  1843. &result.LoanPayment,
  1844. &result.TotalMonthly,
  1845. &result.TotalFees,
  1846. &result.TotalCredits,
  1847. &result.CashToClose,
  1848. )
  1849. if err != nil {
  1850. return result, err
  1851. }
  1852. return result, nil
  1853. }
  1854. // Must have an estimate ID 'e', but not necessarily a loan id 'id'
  1855. func getLoans(db *sql.DB, e int, id int) ([]Loan, error) {
  1856. var loans []Loan
  1857. var query string
  1858. var rows *sql.Rows
  1859. var err error
  1860. query = `SELECT
  1861. l.id,
  1862. l.type_id,
  1863. l.estimate_id,
  1864. l.amount,
  1865. l.term,
  1866. l.interest,
  1867. l.ltv,
  1868. l.dti,
  1869. l.hoi,
  1870. l.tax,
  1871. l.name
  1872. FROM loan l WHERE l.id = CASE @e := ? WHEN 0 THEN l.id ELSE @e END AND
  1873. l.estimate_id = ?
  1874. `
  1875. rows, err = db.Query(query, id, e)
  1876. if err != nil {
  1877. return loans, err
  1878. }
  1879. defer rows.Close()
  1880. for rows.Next() {
  1881. var loan Loan
  1882. if err := rows.Scan(
  1883. &loan.Id,
  1884. &loan.Type.Id,
  1885. &loan.EstimateId,
  1886. &loan.Amount,
  1887. &loan.Term,
  1888. &loan.Interest,
  1889. &loan.Ltv,
  1890. &loan.Dti,
  1891. &loan.Hoi,
  1892. &loan.Tax,
  1893. &loan.Name,
  1894. ); err != nil {
  1895. return loans, err
  1896. }
  1897. mi, err := getMi(db, loan.Id)
  1898. if err != nil {
  1899. return loans, err
  1900. }
  1901. loan.Mi = mi
  1902. fees, err := getFees(db, loan.Id)
  1903. if err != nil {
  1904. return loans, err
  1905. }
  1906. loan.Fees = fees
  1907. loan.Result, err = getResult(db, loan.Id)
  1908. if err != nil {
  1909. return loans, err
  1910. }
  1911. loan.Type, err = getLoanType(db, loan.Type.Id)
  1912. if err != nil {
  1913. return loans, err
  1914. }
  1915. loans = append(loans, loan)
  1916. }
  1917. // Prevents runtime panics
  1918. if len(loans) == 0 {
  1919. return loans, errors.New("Loan not found.")
  1920. }
  1921. return loans, nil
  1922. }
  1923. func getEstimate(db *sql.DB, id int) (Estimate, error) {
  1924. estimates, err := getEstimates(db, id, 0)
  1925. if err != nil {
  1926. return Estimate{}, err
  1927. }
  1928. return estimates[0], nil
  1929. }
  1930. func getEstimates(db *sql.DB, id int, user int) ([]Estimate, error) {
  1931. var estimates []Estimate
  1932. var query string
  1933. var rows *sql.Rows
  1934. var err error
  1935. query = `SELECT
  1936. id,
  1937. user_id,
  1938. transaction,
  1939. price,
  1940. property,
  1941. occupancy,
  1942. zip,
  1943. pud
  1944. FROM estimate WHERE id = CASE @e := ? WHEN 0 THEN id ELSE @e END AND
  1945. user_id = CASE @e := ? WHEN 0 THEN user_id ELSE @e END
  1946. `
  1947. rows, err = db.Query(query, id, user)
  1948. if err != nil {
  1949. return estimates, err
  1950. }
  1951. defer rows.Close()
  1952. for rows.Next() {
  1953. var estimate Estimate
  1954. if err := rows.Scan(
  1955. &estimate.Id,
  1956. &estimate.User,
  1957. &estimate.Transaction,
  1958. &estimate.Price,
  1959. &estimate.Property,
  1960. &estimate.Occupancy,
  1961. &estimate.Zip,
  1962. &estimate.Pud,
  1963. ); err != nil {
  1964. return estimates, err
  1965. }
  1966. err := estimate.getBorrower(db)
  1967. if err != nil {
  1968. return estimates, err
  1969. }
  1970. estimates = append(estimates, estimate)
  1971. }
  1972. // Prevents runtime panics
  1973. if len(estimates) == 0 {
  1974. return estimates, errors.New("Estimate not found.")
  1975. }
  1976. for i := range estimates {
  1977. estimates[i].Loans, err = getLoans(db, estimates[i].Id, 0)
  1978. if err != nil {
  1979. return estimates, err
  1980. }
  1981. }
  1982. return estimates, nil
  1983. }
  1984. func queryETemplates(db *sql.DB, id int, user int) ([]ETemplate, error) {
  1985. var eTemplates []ETemplate
  1986. var query string
  1987. var rows *sql.Rows
  1988. var err error
  1989. query = `SELECT
  1990. id,
  1991. estimate_id,
  1992. user_id,
  1993. branch_id
  1994. FROM estimate_template WHERE id = CASE @e := ? WHEN 0 THEN id ELSE @e END AND
  1995. user_id = CASE @e := ? WHEN 0 THEN user_id ELSE @e END
  1996. `
  1997. rows, err = db.Query(query, id, user)
  1998. if err != nil {
  1999. return eTemplates, err
  2000. }
  2001. defer rows.Close()
  2002. for rows.Next() {
  2003. var e ETemplate
  2004. if err := rows.Scan(
  2005. &e.Id,
  2006. &e.Estimate.Id,
  2007. &e.UserId,
  2008. &e.BranchId,
  2009. ); err != nil {
  2010. return eTemplates, err
  2011. }
  2012. e.Estimate, err = getEstimate(db, e.Estimate.Id)
  2013. if err != nil {
  2014. return eTemplates, err
  2015. }
  2016. eTemplates = append(eTemplates, e)
  2017. }
  2018. return eTemplates, nil
  2019. }
  2020. // Accepts a borrower struct and returns the id of the inserted borrower and
  2021. // any related error.
  2022. func (estimate *Estimate) insertETemplate(db *sql.DB, user int, branch int) error {
  2023. var query string
  2024. var err error
  2025. query = `INSERT INTO estimate_template
  2026. (
  2027. estimate_id,
  2028. user_id,
  2029. branch_id
  2030. )
  2031. VALUES (?, ?, ?)
  2032. `
  2033. _, err = db.Exec(query,
  2034. estimate.Id,
  2035. user,
  2036. branch,
  2037. )
  2038. if err != nil {
  2039. return err
  2040. }
  2041. return nil
  2042. }
  2043. // Accepts a borrower struct and returns the id of the inserted borrower and
  2044. // any related error.
  2045. func (estimate *Estimate) insertBorrower(db *sql.DB) error {
  2046. var query string
  2047. var row *sql.Row
  2048. var err error
  2049. query = `INSERT INTO borrower
  2050. (
  2051. estimate_id,
  2052. credit_score,
  2053. monthly_income,
  2054. num
  2055. )
  2056. VALUES (?, ?, ?, ?)
  2057. RETURNING id
  2058. `
  2059. row = db.QueryRow(query,
  2060. estimate.Id,
  2061. estimate.Borrower.Credit,
  2062. estimate.Borrower.Income,
  2063. estimate.Borrower.Num,
  2064. )
  2065. err = row.Scan(&estimate.Borrower.Id)
  2066. if err != nil {
  2067. return err
  2068. }
  2069. return nil
  2070. }
  2071. func insertMi(db *sql.DB, mi MI) (int, error) {
  2072. var id int
  2073. query := `INSERT INTO mi
  2074. (
  2075. type,
  2076. label,
  2077. lender,
  2078. rate,
  2079. premium,
  2080. upfront,
  2081. five_year_total,
  2082. initial_premium,
  2083. initial_rate,
  2084. initial_amount
  2085. )
  2086. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  2087. RETURNING id`
  2088. row := db.QueryRow(query,
  2089. &mi.Type,
  2090. &mi.Label,
  2091. &mi.Lender,
  2092. &mi.Rate,
  2093. &mi.Premium,
  2094. &mi.Upfront,
  2095. &mi.FiveYearTotal,
  2096. &mi.InitialAllInPremium,
  2097. &mi.InitialAllInRate,
  2098. &mi.InitialAmount,
  2099. )
  2100. err := row.Scan(&id)
  2101. if err != nil {
  2102. return 0, err
  2103. }
  2104. return id, nil
  2105. }
  2106. func insertFee(db *sql.DB, fee Fee) (int, error) {
  2107. var id int
  2108. query := `INSERT INTO fee
  2109. (loan_id, amount, perc, type, notes, name, category)
  2110. VALUES (?, ?, ?, ?, ?, ?, ?)
  2111. RETURNING id`
  2112. row := db.QueryRow(query,
  2113. fee.LoanId,
  2114. fee.Amount,
  2115. fee.Perc,
  2116. fee.Type,
  2117. fee.Notes,
  2118. fee.Name,
  2119. fee.Category,
  2120. )
  2121. err := row.Scan(&id)
  2122. if err != nil {
  2123. return 0, err
  2124. }
  2125. return id, nil
  2126. }
  2127. func insertLoanType(db *sql.DB, lt LoanType) (int, error) {
  2128. var id int
  2129. query := `INSERT INTO loan_type (branch_id, user_id, name)
  2130. VALUES (NULLIF(?, 0), NULLIF(?, 0), ?)
  2131. RETURNING id`
  2132. row := db.QueryRow(query,
  2133. lt.Branch,
  2134. lt.User,
  2135. lt.Name,
  2136. )
  2137. err := row.Scan(&id)
  2138. if err != nil {
  2139. return 0, err
  2140. }
  2141. return id, nil
  2142. }
  2143. func (loan *Loan) insertLoan(db *sql.DB) error {
  2144. var query string
  2145. var row *sql.Row
  2146. var err error
  2147. query = `INSERT INTO loan
  2148. (
  2149. estimate_id,
  2150. type_id,
  2151. amount,
  2152. term,
  2153. interest,
  2154. ltv,
  2155. dti,
  2156. hoi,
  2157. tax,
  2158. name
  2159. )
  2160. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  2161. RETURNING id
  2162. `
  2163. row = db.QueryRow(query,
  2164. loan.EstimateId,
  2165. loan.Type.Id,
  2166. loan.Amount,
  2167. loan.Term,
  2168. loan.Interest,
  2169. loan.Ltv,
  2170. loan.Dti,
  2171. loan.Hoi,
  2172. loan.Tax,
  2173. loan.Name,
  2174. )
  2175. err = row.Scan(&loan.Id)
  2176. if err != nil {
  2177. return err
  2178. }
  2179. _, err = insertMi(db, loan.Mi)
  2180. if err != nil {
  2181. return err
  2182. }
  2183. for i := range loan.Fees {
  2184. loan.Fees[i].LoanId = loan.Id
  2185. _, err := insertFee(db, loan.Fees[i])
  2186. if err != nil {
  2187. return err
  2188. }
  2189. }
  2190. return nil
  2191. }
  2192. func (estimate *Estimate) insertEstimate(db *sql.DB) error {
  2193. var query string
  2194. var row *sql.Row
  2195. var err error
  2196. // var id int // Inserted estimate's id
  2197. query = `INSERT INTO estimate
  2198. (
  2199. user_id,
  2200. transaction,
  2201. price,
  2202. property,
  2203. occupancy,
  2204. zip,
  2205. pud
  2206. )
  2207. VALUES (?, ?, ?, ?, ?, ?, ?)
  2208. RETURNING id
  2209. `
  2210. row = db.QueryRow(query,
  2211. estimate.User,
  2212. estimate.Transaction,
  2213. estimate.Price,
  2214. estimate.Property,
  2215. estimate.Occupancy,
  2216. estimate.Zip,
  2217. estimate.Pud,
  2218. )
  2219. err = row.Scan(&estimate.Id)
  2220. if err != nil {
  2221. return err
  2222. }
  2223. err = estimate.insertBorrower(db)
  2224. if err != nil {
  2225. return err
  2226. }
  2227. for i := range estimate.Loans {
  2228. estimate.Loans[i].EstimateId = estimate.Id
  2229. err = estimate.Loans[i].insertLoan(db)
  2230. if err != nil {
  2231. return err
  2232. }
  2233. }
  2234. return nil
  2235. }
  2236. func (estimate *Estimate) del(db *sql.DB, user int) error {
  2237. var query string
  2238. var err error
  2239. query = `DELETE FROM estimate WHERE id = ? AND user_id = ?`
  2240. _, err = db.Exec(query, estimate.Id, user)
  2241. if err != nil {
  2242. return err
  2243. }
  2244. return nil
  2245. }
  2246. func (et *ETemplate) del(db *sql.DB, user int) error {
  2247. var query string
  2248. var err error
  2249. query = `DELETE FROM estimate_template WHERE id = ? AND user_id = ?`
  2250. _, err = db.Exec(query, et.Id, user)
  2251. if err != nil {
  2252. return err
  2253. }
  2254. return nil
  2255. }
  2256. func (eTemplate *ETemplate) insert(db *sql.DB) error {
  2257. var query string
  2258. var row *sql.Row
  2259. var err error
  2260. query = `INSERT INTO estimate_template
  2261. (
  2262. user_id,
  2263. branch_id,
  2264. estimate_id,
  2265. )
  2266. VALUES (?, ?, ?)
  2267. RETURNING id
  2268. `
  2269. row = db.QueryRow(query,
  2270. eTemplate.UserId,
  2271. eTemplate.BranchId,
  2272. eTemplate.Estimate.Id,
  2273. )
  2274. err = row.Scan(&eTemplate.Id)
  2275. if err != nil {
  2276. return err
  2277. }
  2278. return nil
  2279. }
  2280. func createEstimate(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2281. var estimate Estimate
  2282. err := json.NewDecoder(r.Body).Decode(&estimate)
  2283. if err != nil {
  2284. http.Error(w, "Invalid fields.", 422)
  2285. return
  2286. }
  2287. claims, err := getClaims(r)
  2288. estimate.User = claims.Id
  2289. err = estimate.insertEstimate(db)
  2290. if err != nil {
  2291. http.Error(w, err.Error(), 422)
  2292. return
  2293. }
  2294. estimate.makeResults()
  2295. err = estimate.insertResults(db)
  2296. if err != nil {
  2297. http.Error(w, err.Error(), 500)
  2298. return
  2299. }
  2300. e, err := getEstimates(db, estimate.Id, 0)
  2301. if err != nil {
  2302. http.Error(w, err.Error(), 500)
  2303. return
  2304. }
  2305. json.NewEncoder(w).Encode(e[0])
  2306. }
  2307. // Query all estimates that belong to the current user
  2308. func fetchEstimate(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2309. var estimates []Estimate
  2310. claims, err := getClaims(r)
  2311. estimates, err = getEstimates(db, 0, claims.Id)
  2312. if err != nil {
  2313. http.Error(w, err.Error(), 500)
  2314. return
  2315. }
  2316. json.NewEncoder(w).Encode(estimates)
  2317. }
  2318. func checkConventional(l Loan, b Borrower) error {
  2319. if b.Credit < 620 {
  2320. return errors.New("Credit score too low for conventional loan")
  2321. }
  2322. // Buyer needs to put down 20% to avoid mortgage insurance
  2323. if l.Ltv > 80 && l.Mi.Rate == 0 {
  2324. return errors.New(fmt.Sprintln(
  2325. l.Name,
  2326. "down payment must be 20% to avoid insurance",
  2327. ))
  2328. }
  2329. return nil
  2330. }
  2331. func checkFHA(l Loan, b Borrower) error {
  2332. if b.Credit < 500 {
  2333. return errors.New("Credit score too low for FHA loan")
  2334. }
  2335. if l.Ltv > 96.5 {
  2336. return errors.New("FHA down payment must be at least 3.5%")
  2337. }
  2338. if b.Credit < 580 && l.Ltv > 90 {
  2339. return errors.New("FHA down payment must be at least 10%")
  2340. }
  2341. // Debt-to-income must be below 45% if credit score is below 580.
  2342. if b.Credit < 580 && l.Dti > 45 {
  2343. return errors.New(fmt.Sprintln(
  2344. l.Name, "debt to income is too high for credit score.",
  2345. ))
  2346. }
  2347. return nil
  2348. }
  2349. // Loan option for veterans with no set rules. Mainly placeholder.
  2350. func checkVA(l Loan, b Borrower) error {
  2351. return nil
  2352. }
  2353. // Loan option for residents of rural areas with no set rules.
  2354. // Mainly placeholder.
  2355. func checkUSDA(l Loan, b Borrower) error {
  2356. return nil
  2357. }
  2358. // Should also check loan amount limit maybe with an API.
  2359. func checkEstimate(e Estimate) error {
  2360. if e.Property == "" {
  2361. return errors.New("Empty property type")
  2362. }
  2363. if e.Price == 0 {
  2364. return errors.New("Empty property price")
  2365. }
  2366. if e.Borrower.Num == 0 {
  2367. return errors.New("Missing number of borrowers")
  2368. }
  2369. if e.Borrower.Credit == 0 {
  2370. return errors.New("Missing borrower credit score")
  2371. }
  2372. if e.Borrower.Income == 0 {
  2373. return errors.New("Missing borrower credit income")
  2374. }
  2375. for _, l := range e.Loans {
  2376. if l.Amount == 0 {
  2377. return errors.New(fmt.Sprintln(l.Name, "loan amount cannot be zero"))
  2378. }
  2379. if l.Term == 0 {
  2380. return errors.New(fmt.Sprintln(l.Name, "loan term cannot be zero"))
  2381. }
  2382. if l.Interest == 0 {
  2383. return errors.New(fmt.Sprintln(l.Name, "loan interest cannot be zero"))
  2384. }
  2385. // Can be used to check rules for specific loan types
  2386. var err error
  2387. switch l.Type.Id {
  2388. case 1:
  2389. err = checkConventional(l, e.Borrower)
  2390. case 2:
  2391. err = checkFHA(l, e.Borrower)
  2392. case 3:
  2393. err = checkVA(l, e.Borrower)
  2394. case 4:
  2395. err = checkUSDA(l, e.Borrower)
  2396. default:
  2397. err = errors.New("Invalid loan type")
  2398. }
  2399. if err != nil {
  2400. return err
  2401. }
  2402. }
  2403. return nil
  2404. }
  2405. func validateEstimate(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2406. var estimate Estimate
  2407. err := json.NewDecoder(r.Body).Decode(&estimate)
  2408. if err != nil {
  2409. http.Error(w, err.Error(), 422)
  2410. return
  2411. }
  2412. err = checkEstimate(estimate)
  2413. if err != nil {
  2414. http.Error(w, err.Error(), 406)
  2415. return
  2416. }
  2417. }
  2418. func checkPdf(w http.ResponseWriter, r *http.Request) {
  2419. db, err := sql.Open("mysql",
  2420. fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/skouter_dev",
  2421. os.Getenv("DB_USER"),
  2422. os.Getenv("DB_PASSWORD")))
  2423. // w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  2424. err = db.Ping()
  2425. if err != nil {
  2426. fmt.Println("Bad database configuration: %v\n", err)
  2427. panic(err)
  2428. // maybe os.Exit(1) instead
  2429. }
  2430. estimates, err := getEstimates(db, 1, 0)
  2431. if err != nil {
  2432. w.WriteHeader(500)
  2433. return
  2434. }
  2435. // claims, err := getClaims(r)
  2436. if err != nil {
  2437. w.WriteHeader(500)
  2438. return
  2439. }
  2440. user, err := queryUser(db, 1)
  2441. info := Report{
  2442. Title: "test PDF",
  2443. Name: "idk-random-name",
  2444. User: user,
  2445. Estimate: estimates[0],
  2446. }
  2447. avatar, err := fetchAvatar(db, info.User.Id)
  2448. letterhead, err := fetchLetterhead(db, info.User.Id)
  2449. info.Avatar =
  2450. base64.StdEncoding.EncodeToString(avatar)
  2451. info.Letterhead =
  2452. base64.StdEncoding.EncodeToString(letterhead)
  2453. for l := range info.Estimate.Loans {
  2454. loan := info.Estimate.Loans[l]
  2455. for f := range info.Estimate.Loans[l].Fees {
  2456. if info.Estimate.Loans[l].Fees[f].Amount < 0 {
  2457. loan.Credits = append(loan.Credits, loan.Fees[f])
  2458. }
  2459. }
  2460. }
  2461. err = pages["report"].tpl.ExecuteTemplate(w, "master.tpl", info)
  2462. if err != nil {
  2463. fmt.Println(err)
  2464. }
  2465. }
  2466. func getETemplates(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2467. claims, err := getClaims(r)
  2468. et, err := queryETemplates(db, 0, claims.Id)
  2469. if err != nil {
  2470. http.Error(w, err.Error(), 500)
  2471. return
  2472. }
  2473. json.NewEncoder(w).Encode(et)
  2474. }
  2475. func createETemplate(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2476. var estimate Estimate
  2477. err := json.NewDecoder(r.Body).Decode(&estimate)
  2478. if err != nil {
  2479. http.Error(w, err.Error(), 422)
  2480. return
  2481. }
  2482. claims, err := getClaims(r)
  2483. if err != nil {
  2484. http.Error(w, err.Error(), 422)
  2485. return
  2486. }
  2487. err = estimate.insertETemplate(db, claims.Id, 0)
  2488. if err != nil {
  2489. http.Error(w, err.Error(), 500)
  2490. return
  2491. }
  2492. }
  2493. func getPdf(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2494. var estimate Estimate
  2495. err := json.NewDecoder(r.Body).Decode(&estimate)
  2496. cmd := exec.Command("wkhtmltopdf", "-", "-")
  2497. stdout, err := cmd.StdoutPipe()
  2498. if err != nil {
  2499. w.WriteHeader(500)
  2500. log.Println(err)
  2501. return
  2502. }
  2503. stdin, err := cmd.StdinPipe()
  2504. if err != nil {
  2505. w.WriteHeader(500)
  2506. log.Println(err)
  2507. return
  2508. }
  2509. if err := cmd.Start(); err != nil {
  2510. log.Fatal(err)
  2511. }
  2512. claims, err := getClaims(r)
  2513. if err != nil {
  2514. w.WriteHeader(500)
  2515. log.Println(err)
  2516. return
  2517. }
  2518. user, err := queryUser(db, claims.Id)
  2519. info := Report{
  2520. Title: "test PDF",
  2521. Name: "idk-random-name",
  2522. User: user,
  2523. Estimate: estimate,
  2524. }
  2525. avatar, err := fetchAvatar(db, info.User.Id)
  2526. letterhead, err := fetchLetterhead(db, info.User.Id)
  2527. if len(avatar) > 1 {
  2528. info.Avatar =
  2529. base64.StdEncoding.EncodeToString(avatar)
  2530. }
  2531. if len(letterhead) > 1 {
  2532. info.Letterhead =
  2533. base64.StdEncoding.EncodeToString(letterhead)
  2534. }
  2535. err = pages["report"].tpl.ExecuteTemplate(stdin, "master.tpl", info)
  2536. if err != nil {
  2537. w.WriteHeader(500)
  2538. log.Println(err)
  2539. return
  2540. }
  2541. stdin.Close()
  2542. buf, err := io.ReadAll(stdout)
  2543. if _, err := w.Write(buf); err != nil {
  2544. w.WriteHeader(500)
  2545. log.Println(err)
  2546. return
  2547. }
  2548. if err := cmd.Wait(); err != nil {
  2549. log.Println(err)
  2550. return
  2551. }
  2552. }
  2553. func clipLetterhead(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2554. var validTypes []string = []string{"image/png", "image/jpeg"}
  2555. var isValidType bool
  2556. var err error
  2557. // claims, err := getClaims(r)
  2558. if err != nil {
  2559. http.Error(w, "Invalid token.", 422)
  2560. return
  2561. }
  2562. img, t, err := image.Decode(r.Body)
  2563. if err != nil {
  2564. http.Error(w, "Invalid file, JPEG and PNG only.", 422)
  2565. return
  2566. }
  2567. for _, v := range validTypes {
  2568. if v == "image/"+t {
  2569. isValidType = true
  2570. }
  2571. }
  2572. if !isValidType {
  2573. http.Error(w, "Invalid file type.", 422)
  2574. return
  2575. }
  2576. g := gift.New(
  2577. gift.ResizeToFit(400, 200, gift.LanczosResampling),
  2578. )
  2579. dst := image.NewRGBA(g.Bounds(img.Bounds()))
  2580. g.Draw(dst, img)
  2581. w.Header().Set("Content-Type", "image/png")
  2582. err = png.Encode(w, dst)
  2583. if err != nil {
  2584. http.Error(w, "Error encoding.", 500)
  2585. return
  2586. }
  2587. }
  2588. func createCustomer(name string, email string, address Address) (
  2589. stripe.Customer, error) {
  2590. params := &stripe.CustomerParams{
  2591. Email: stripe.String(email),
  2592. Name: stripe.String(name),
  2593. Address: &stripe.AddressParams{
  2594. City: stripe.String(address.City),
  2595. Country: stripe.String(address.Country),
  2596. Line1: stripe.String(address.Street),
  2597. PostalCode: stripe.String(address.Zip),
  2598. State: stripe.String(address.Region),
  2599. },
  2600. };
  2601. result, err := customer.New(params)
  2602. return *result, err
  2603. }
  2604. // Initiates a new standard subscription using a given customer ID
  2605. func createSubscription(cid string) (*stripe.Subscription, error) {
  2606. // Automatically save the payment method to the subscription
  2607. // when the first payment is successful.
  2608. paymentSettings := &stripe.SubscriptionPaymentSettingsParams{
  2609. SaveDefaultPaymentMethod: stripe.String("on_subscription"),
  2610. }
  2611. // Create the subscription. Note we're expanding the Subscription's
  2612. // latest invoice and that invoice's payment_intent
  2613. // so we can pass it to the front end to confirm the payment
  2614. subscriptionParams := &stripe.SubscriptionParams{
  2615. Customer: stripe.String(cid),
  2616. Items: []*stripe.SubscriptionItemsParams{
  2617. {
  2618. Price: stripe.String(standardPriceId),
  2619. },
  2620. },
  2621. PaymentSettings: paymentSettings,
  2622. PaymentBehavior: stripe.String("default_incomplete"),
  2623. }
  2624. subscriptionParams.AddExpand("latest_invoice.payment_intent")
  2625. s, err := subscription.New(subscriptionParams)
  2626. return s, err
  2627. }
  2628. // Initiates a new trial subscription using a given customer ID
  2629. func createTrialSubscription(cid string) (*stripe.Subscription, error) {
  2630. // Automatically save the payment method to the subscription
  2631. // when the first payment is successful.
  2632. paymentSettings := &stripe.SubscriptionPaymentSettingsParams{
  2633. SaveDefaultPaymentMethod: stripe.String("on_subscription"),
  2634. }
  2635. // Create the subscription. Note we're expanding the Subscription's
  2636. // latest invoice and that invoice's payment_intent
  2637. // so we can pass it to the front end to confirm the payment
  2638. subscriptionParams := &stripe.SubscriptionParams{
  2639. Customer: stripe.String(cid),
  2640. Items: []*stripe.SubscriptionItemsParams{
  2641. {
  2642. Price: stripe.String(standardPriceId),
  2643. },
  2644. },
  2645. TrialPeriodDays: stripe.Int64(30),
  2646. PaymentSettings: paymentSettings,
  2647. PaymentBehavior: stripe.String("default_incomplete"),
  2648. }
  2649. subscriptionParams.AddExpand("latest_invoice.payment_intent")
  2650. s, err := subscription.New(subscriptionParams)
  2651. return s, err
  2652. }
  2653. func ( user *User ) SyncSub( sub *stripe.Subscription, db *sql.DB ) error {
  2654. var err error
  2655. user.Sub.UserId = user.Id
  2656. user.Sub.StripeId = sub.ID
  2657. user.Sub.CustomerId = user.CustomerId
  2658. user.Sub.PriceId = standardPriceId
  2659. user.Sub.End = int(sub.CurrentPeriodEnd)
  2660. user.Sub.Start = int(sub.CurrentPeriodStart)
  2661. user.Sub.ClientSecret = sub.LatestInvoice.PaymentIntent.ClientSecret
  2662. user.Sub.PaymentStatus = string(sub.LatestInvoice.PaymentIntent.Status)
  2663. user.Sub.Status = string(sub.Status)
  2664. if user.Sub.Id != 0 {
  2665. err = user.Sub.insertSub(db)
  2666. } else {
  2667. user.Sub.updateSub(db)
  2668. }
  2669. return err
  2670. }
  2671. // Creates a new subscription instance for a new user or retrieves the
  2672. // existing instance if possible. It's main purpose is to supply a
  2673. // client secret used for sending billing information to stripe.
  2674. func subscribe(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2675. claims, err := getClaims(r)
  2676. user, err := queryUser(db, claims.Id)
  2677. if err != nil {
  2678. w.WriteHeader(422)
  2679. return
  2680. }
  2681. user.querySub(db)
  2682. var name string = user.FirstName + " " + user.LastName
  2683. if user.CustomerId == "" {
  2684. c, err := createCustomer(name, user.Email, user.Address)
  2685. if err != nil {
  2686. http.Error(w, err.Error(), 500)
  2687. return
  2688. }
  2689. err = user.updateCustomerId(db, c.ID)
  2690. if err != nil {
  2691. http.Error(w, err.Error(), 500)
  2692. return
  2693. }
  2694. }
  2695. if user.Sub.Id == 0 {
  2696. s, err := createSubscription(user.CustomerId)
  2697. if err != nil {
  2698. http.Error(w, err.Error(), 500)
  2699. return
  2700. }
  2701. user.Sub.UserId = user.Id
  2702. user.Sub.StripeId = s.ID
  2703. user.Sub.CustomerId = user.CustomerId
  2704. user.Sub.PriceId = standardPriceId
  2705. user.Sub.End = int(s.CurrentPeriodEnd)
  2706. user.Sub.Start = int(s.CurrentPeriodStart)
  2707. user.Sub.ClientSecret = s.LatestInvoice.PaymentIntent.ClientSecret
  2708. user.Sub.PaymentStatus = string(s.LatestInvoice.PaymentIntent.Status)
  2709. // Inserting from here is unnecessary and confusing because
  2710. // new subs are already handled by the stripe hook. It remains for
  2711. // easier testing of the endpoint.
  2712. err = user.Sub.insertSub(db)
  2713. if err != nil {
  2714. http.Error(w, err.Error(), 500)
  2715. return
  2716. }
  2717. } else {
  2718. // This should handle creating a new subscription when the old one
  2719. // has an incomplete_expired status and cannot be paid
  2720. }
  2721. json.NewEncoder(w).Encode(user.Sub)
  2722. }
  2723. // Creates a new subscription instance for a new user or retrieves the
  2724. // existing instance if possible. It's main purpose is to supply a
  2725. // client secret used for sending billing information to stripe.
  2726. func trialSubscribe(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2727. claims, err := getClaims(r)
  2728. user, err := queryUser(db, claims.Id)
  2729. if err != nil {
  2730. w.WriteHeader(422)
  2731. return
  2732. }
  2733. user.querySub(db)
  2734. var name string = user.FirstName + " " + user.LastName
  2735. if user.CustomerId == "" {
  2736. c, err := createCustomer(name, user.Email, user.Address)
  2737. if err != nil {
  2738. http.Error(w, err.Error(), 500)
  2739. return
  2740. }
  2741. err = user.updateCustomerId(db, c.ID)
  2742. if err != nil {
  2743. http.Error(w, err.Error(), 500)
  2744. return
  2745. }
  2746. }
  2747. if user.Sub.Id == 0 {
  2748. s, err := createTrialSubscription(user.CustomerId)
  2749. if err != nil {
  2750. http.Error(w, err.Error(), 500)
  2751. return
  2752. }
  2753. user.Sub.UserId = user.Id
  2754. user.Sub.StripeId = s.ID
  2755. user.Sub.CustomerId = user.CustomerId
  2756. user.Sub.PriceId = standardPriceId
  2757. user.Sub.End = int(s.CurrentPeriodEnd)
  2758. user.Sub.Start = int(s.CurrentPeriodStart)
  2759. user.Sub.ClientSecret = s.LatestInvoice.PaymentIntent.ClientSecret
  2760. user.Sub.PaymentStatus = string(s.LatestInvoice.PaymentIntent.Status)
  2761. // Inserting from here is unnecessary and confusing because
  2762. // new subs are already handled by the stripe hook. It remains for
  2763. // easier testing of the endpoint.
  2764. err = user.Sub.insertSub(db)
  2765. if err != nil {
  2766. http.Error(w, err.Error(), 500)
  2767. return
  2768. }
  2769. } else {
  2770. // This should handle creating a new subscription when the old one
  2771. // has an incomplete_expired status and cannot be paid
  2772. }
  2773. json.NewEncoder(w).Encode(user.Sub)
  2774. }
  2775. // A successful subscription payment should be confirmed by Stripe and
  2776. // Updated through this hook.
  2777. func invoicePaid(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2778. var invoice stripe.Invoice
  2779. b, err := io.ReadAll(r.Body)
  2780. if err != nil {
  2781. http.Error(w, err.Error(), http.StatusBadRequest)
  2782. log.Printf("io.ReadAll: %v", err)
  2783. return
  2784. }
  2785. event, err := webhook.ConstructEvent(b,
  2786. r.Header.Get("Stripe-Signature"),
  2787. hookKeys.InvoicePaid)
  2788. if err != nil {
  2789. http.Error(w, err.Error(), http.StatusBadRequest)
  2790. log.Printf("webhook.ConstructEvent: %v", err)
  2791. return
  2792. }
  2793. // OK should be sent before any processing to confirm with Stripe that
  2794. // the hook was received
  2795. w.WriteHeader(http.StatusOK)
  2796. if event.Type != "invoice.paid" {
  2797. log.Println("Invalid event type sent to invoice-paid.")
  2798. return
  2799. }
  2800. json.Unmarshal(event.Data.Raw, &invoice)
  2801. log.Println(event.Type, invoice.ID, invoice.Customer.ID)
  2802. user, err := queryCustomer(db, invoice.Customer.ID)
  2803. if err != nil {
  2804. log.Printf("Could not query customer: %v", err)
  2805. return
  2806. }
  2807. s, err := subscription.Get(invoice.Subscription.ID, nil)
  2808. if err != nil {
  2809. log.Printf("Could not fetch subscription: %v", err)
  2810. return
  2811. }
  2812. log.Println(user.Id, s.ID)
  2813. }
  2814. func invoiceFailed(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2815. b, err := io.ReadAll(r.Body)
  2816. if err != nil {
  2817. http.Error(w, err.Error(), http.StatusBadRequest)
  2818. log.Printf("io.ReadAll: %v", err)
  2819. return
  2820. }
  2821. event, err := webhook.ConstructEvent(b, r.Header.Get("Stripe-Signature"),
  2822. os.Getenv("STRIPE_SECRET_KEY"))
  2823. if err != nil {
  2824. http.Error(w, err.Error(), http.StatusBadRequest)
  2825. log.Printf("webhook.ConstructEvent: %v", err)
  2826. return
  2827. }
  2828. log.Println(event.Data)
  2829. }
  2830. // Important for catching subscription creation through Stripe dashboard
  2831. // although it already happens at subscribe().
  2832. func subCreated(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2833. var sub stripe.Subscription
  2834. var err error
  2835. event, err := constructEvent(r, hookKeys.SubCreated)
  2836. if err != nil {
  2837. http.Error(w, err.Error(), http.StatusBadRequest)
  2838. return
  2839. }
  2840. // OK should be sent before any processing to confirm with Stripe that
  2841. // the hook was received
  2842. w.WriteHeader(http.StatusOK)
  2843. if event.Type != "customer.subscription.created" {
  2844. log.Println(
  2845. "Invalid event type. Expecting customer.subscription.created.")
  2846. return
  2847. }
  2848. json.Unmarshal(event.Data.Raw, &sub)
  2849. log.Println(event.Type, sub.ID, sub.Customer.ID)
  2850. user, err := queryCustomer(db, sub.Customer.ID)
  2851. if err != nil {
  2852. log.Printf("Could not query customer: %v", err)
  2853. return
  2854. }
  2855. if statuses[user.Status] < 5 && sub.Status == "trialing" {
  2856. user.Status = "Trial"
  2857. user.update(db)
  2858. } else if sub.Status != "active" {
  2859. user.Status = "Unsubscribed"
  2860. user.update(db)
  2861. }
  2862. err = user.SyncSub(&sub, db)
  2863. if err != nil {
  2864. http.Error(w, err.Error(), 500)
  2865. return
  2866. }
  2867. log.Println("User subscription created:", user.Id, sub.ID)
  2868. }
  2869. // Checks if the user already has a subscription and replaces those
  2870. // fields if necessary.
  2871. func subUpdated(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2872. var sub stripe.Subscription
  2873. var err error
  2874. event, err := constructEvent(r, hookKeys.SubUpdated)
  2875. if err != nil {
  2876. http.Error(w, err.Error(), http.StatusBadRequest)
  2877. return
  2878. }
  2879. // OK should be sent before any processing to confirm with Stripe that
  2880. // the hook was received
  2881. w.WriteHeader(http.StatusOK)
  2882. if event.Type != "customer.subscription.updated" {
  2883. log.Println(
  2884. "Invalid event type sent. Expecting customer.subscription.updated.")
  2885. return
  2886. }
  2887. json.Unmarshal(event.Data.Raw, &sub)
  2888. log.Println(event.Type, sub.ID, sub.Customer.ID)
  2889. user, err := queryCustomer(db, sub.Customer.ID)
  2890. if err != nil {
  2891. log.Printf("Could not query customer: %v", err)
  2892. return
  2893. }
  2894. if statuses[user.Status] < 5 && sub.Status == "trialing" {
  2895. user.Status = "Trial"
  2896. user.update(db)
  2897. } else if sub.Status != "active" {
  2898. user.Status = "Unsubscribed"
  2899. user.update(db)
  2900. }
  2901. err = user.SyncSub(&sub, db)
  2902. if err != nil {
  2903. http.Error(w, err.Error(), 500)
  2904. return
  2905. }
  2906. log.Println("User subscription created:", user.Id, sub.ID)
  2907. }
  2908. // Handles deleted subscriptions hooks sent by Stripe
  2909. func subDeleted(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2910. var sub stripe.Subscription
  2911. var err error
  2912. event, err := constructEvent(r, hookKeys.SubDeleted)
  2913. if err != nil {
  2914. http.Error(w, err.Error(), http.StatusBadRequest)
  2915. return
  2916. }
  2917. // OK should be sent before any processing to confirm with Stripe that
  2918. // the hook was received
  2919. w.WriteHeader(http.StatusOK)
  2920. if event.Type != "customer.subscription.deleted" {
  2921. log.Println(
  2922. "Invalid event type sent. Expecting customer.subscription.deleted.")
  2923. return
  2924. }
  2925. json.Unmarshal(event.Data.Raw, &sub)
  2926. log.Println(event.Type, sub.ID, sub.Customer.ID)
  2927. user, err := queryCustomer(db, sub.Customer.ID)
  2928. if err != nil {
  2929. log.Printf("Could not query customer: %v", err)
  2930. return
  2931. }
  2932. if statuses[user.Status] < 5 && sub.Status == "trialing" {
  2933. user.Status = "Trial"
  2934. user.update(db)
  2935. } else if sub.Status != "active" {
  2936. user.Status = "Unsubscribed"
  2937. user.update(db)
  2938. }
  2939. user.Sub.Status = "canceled"
  2940. err = user.SyncSub(&sub, db)
  2941. if err != nil {
  2942. http.Error(w, err.Error(), 500)
  2943. return
  2944. }
  2945. log.Println("User subscription created:", user.Id, sub.ID)
  2946. }
  2947. func verificationToken(id int) (string, error) {
  2948. token := jwt.NewWithClaims(jwt.SigningMethodHS256,
  2949. VerificationClaims{Id: id,
  2950. Exp: time.Now().Add(time.Hour * 48).Format(time.UnixDate)})
  2951. tokenStr, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
  2952. if err != nil {
  2953. log.Println("Verification could not be signed: ", err)
  2954. return tokenStr, err
  2955. }
  2956. return tokenStr, nil
  2957. }
  2958. func verifyUser(w http.ResponseWriter, db *sql.DB, r *http.Request) {
  2959. var claims VerificationClaims
  2960. params, err := url.ParseQuery(r.URL.Path)
  2961. if err != nil {
  2962. w.WriteHeader(500)
  2963. log.Println(err)
  2964. return
  2965. }
  2966. tokenStr := params.Get("verification_token")
  2967. // Pull token payload into UserClaims
  2968. _, err = jwt.ParseWithClaims(tokenStr, &claims,
  2969. func(token *jwt.Token) (any, error) {
  2970. return []byte(os.Getenv("JWT_SECRET")), nil
  2971. })
  2972. if err != nil {
  2973. w.WriteHeader(500)
  2974. log.Println("Could not parse verification claim.")
  2975. return
  2976. }
  2977. if err = claims.Valid(); err != nil {
  2978. w.WriteHeader(500)
  2979. log.Println("Verification claim invalid. ID:", claims.Id)
  2980. return
  2981. }
  2982. }
  2983. func (user *User) sendVerificationEmail() {
  2984. auth := smtp.PlainAuth("",
  2985. os.Getenv("SMTP_USERNAME"),
  2986. os.Getenv("SMTP_PASSWORD"),
  2987. os.Getenv("SMTP_HOST"))
  2988. address := os.Getenv("SMTP_HOST") + ":" + os.Getenv("SMTP_PORT")
  2989. message := `Subject: Email Verification
  2990. Welcome %s,
  2991. Click the link below to verify your email address
  2992. https://skouter.net?verification_token=%s`
  2993. t, err := verificationToken(user.Id)
  2994. if err != nil { return }
  2995. message = fmt.Sprintf(message, user.FirstName, t)
  2996. err = smtp.SendMail(address,
  2997. auth,
  2998. os.Getenv("SMTP_EMAIL"),
  2999. []string{user.Email},
  3000. []byte(message))
  3001. if err != nil {
  3002. fmt.Println(err)
  3003. return
  3004. }
  3005. log.Println("Email Sent Successfully!")
  3006. }
  3007. func api(w http.ResponseWriter, r *http.Request) {
  3008. var args []string
  3009. p := r.URL.Path
  3010. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s",
  3011. os.Getenv("DB_USER"),
  3012. os.Getenv("DB_PASSWORD"),
  3013. os.Getenv("DB_NAME"),
  3014. ))
  3015. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  3016. err = db.Ping()
  3017. if err != nil {
  3018. fmt.Println("Bad database configuration: %v\n", err)
  3019. panic(err)
  3020. // maybe os.Exit(1) instead
  3021. }
  3022. refreshToken(w, db, r)
  3023. switch {
  3024. case match(p, "/api/refreshTokeen", &args):
  3025. // Dummy case to trigger refreshToken() without sending 404
  3026. case match(p, "/api/login", &args) &&
  3027. r.Method == http.MethodPost:
  3028. login(w, db, r)
  3029. case match(p, "/api/token", &args) &&
  3030. r.Method == http.MethodGet && guard(r, 1):
  3031. refreshToken(w, db, r)
  3032. case match(p, "/api/letterhead", &args) &&
  3033. r.Method == http.MethodPost && guard(r, 1):
  3034. clipLetterhead(w, db, r)
  3035. case match(p, "/api/users", &args) && // Array of all users
  3036. r.Method == http.MethodGet && guard(r, 3):
  3037. getUsers(w, db, r)
  3038. case match(p, "/api/user", &args) &&
  3039. r.Method == http.MethodGet && guard(r, 1):
  3040. getUser(w, db, r)
  3041. case match(p, "/api/user", &args) &&
  3042. r.Method == http.MethodPost:
  3043. createUser(w, db, r)
  3044. case match(p, "/api/user", &args) &&
  3045. r.Method == http.MethodPatch &&
  3046. guard(r, 3): // For admin to modify any user
  3047. patchUser(w, db, r)
  3048. case match(p, "/api/user", &args) &&
  3049. r.Method == http.MethodPatch &&
  3050. guard(r, 1): // For employees to modify own accounts
  3051. patchSelf(w, db, r)
  3052. case match(p, "/api/user", &args) &&
  3053. r.Method == http.MethodDelete &&
  3054. guard(r, 3):
  3055. deleteUser(w, db, r)
  3056. case match(p, "/api/user/verify", &args) &&
  3057. r.Method == http.MethodGet:
  3058. verifyUser(w, db, r)
  3059. case match(p, "/api/user/avatar", &args) &&
  3060. r.Method == http.MethodGet &&
  3061. guard(r, 1):
  3062. getAvatar(w, db, r)
  3063. case match(p, "/api/user/avatar", &args) &&
  3064. r.Method == http.MethodPost &&
  3065. guard(r, 1):
  3066. setAvatar(w, db, r)
  3067. case match(p, "/api/user/letterhead", &args) &&
  3068. r.Method == http.MethodGet &&
  3069. guard(r, 1):
  3070. getLetterhead(w, db, r)
  3071. case match(p, "/api/user/letterhead", &args) &&
  3072. r.Method == http.MethodPost &&
  3073. guard(r, 1):
  3074. setLetterhead(w, db, r)
  3075. case match(p, "/api/user/password", &args) &&
  3076. r.Method == http.MethodPost &&
  3077. guard(r, 1):
  3078. changePassword(w, db, r)
  3079. case match(p, "/api/user/subscribe", &args) &&
  3080. r.Method == http.MethodPost &&
  3081. guard(r, 1):
  3082. subscribe(w, db, r)
  3083. case match(p, "/api/user/trial", &args) &&
  3084. r.Method == http.MethodPost &&
  3085. guard(r, 1):
  3086. trialSubscribe(w, db, r)
  3087. case match(p, "/api/fees", &args) &&
  3088. r.Method == http.MethodGet &&
  3089. guard(r, 1):
  3090. getFeesTemp(w, db, r)
  3091. case match(p, "/api/fee", &args) &&
  3092. r.Method == http.MethodPost &&
  3093. guard(r, 1):
  3094. createFeesTemp(w, db, r)
  3095. case match(p, "/api/fee", &args) &&
  3096. r.Method == http.MethodDelete &&
  3097. guard(r, 1):
  3098. deleteFeeTemp(w, db, r)
  3099. case match(p, "/api/estimates", &args) &&
  3100. r.Method == http.MethodGet &&
  3101. guard(r, 1):
  3102. fetchEstimate(w, db, r)
  3103. case match(p, "/api/estimate", &args) &&
  3104. r.Method == http.MethodPost &&
  3105. guard(r, 1):
  3106. createEstimate(w, db, r)
  3107. case match(p, "/api/estimate", &args) &&
  3108. r.Method == http.MethodDelete &&
  3109. guard(r, 1):
  3110. deleteEstimate(w, db, r)
  3111. case match(p, "/api/estimate/validate", &args) &&
  3112. r.Method == http.MethodPost &&
  3113. guard(r, 1):
  3114. validateEstimate(w, db, r)
  3115. case match(p, "/api/estimate/summarize", &args) &&
  3116. r.Method == http.MethodPost &&
  3117. guard(r, 1):
  3118. summarize(w, db, r)
  3119. case match(p, "/api/templates", &args) &&
  3120. r.Method == http.MethodGet &&
  3121. guard(r, 1):
  3122. getETemplates(w, db, r)
  3123. case match(p, "/api/templates", &args) &&
  3124. r.Method == http.MethodPost &&
  3125. guard(r, 1):
  3126. createETemplate(w, db, r)
  3127. case match(p, "/api/templates", &args) &&
  3128. r.Method == http.MethodDelete &&
  3129. guard(r, 1):
  3130. deleteET(w, db, r)
  3131. case match(p, "/api/pdf", &args) &&
  3132. r.Method == http.MethodPost &&
  3133. guard(r, 1):
  3134. getPdf(w, db, r)
  3135. case match(p, "/api/stripe/invoice-paid", &args) &&
  3136. r.Method == http.MethodPost:
  3137. invoicePaid(w, db, r)
  3138. case match(p, "/api/stripe/invoice-payment-failed", &args) &&
  3139. r.Method == http.MethodPost:
  3140. invoiceFailed(w, db, r)
  3141. case match(p, "/api/stripe/sub-created", &args) &&
  3142. r.Method == http.MethodPost:
  3143. subCreated(w, db, r)
  3144. case match(p, "/api/stripe/sub-updated", &args) &&
  3145. r.Method == http.MethodPost:
  3146. subUpdated(w, db, r)
  3147. case match(p, "/api/stripe/sub-deleted", &args) &&
  3148. r.Method == http.MethodPost:
  3149. subDeleted(w, db, r)
  3150. default:
  3151. http.Error(w, "Invalid route or token", 404)
  3152. }
  3153. db.Close()
  3154. }
  3155. // The grav frontend does not have controllers to communicate state
  3156. // with backend so the user's login status must be represented by a
  3157. // query parameter during proxy.
  3158. func setupProxy(r *httputil.ProxyRequest) {
  3159. proxyURL, err := url.Parse("http://localhost:8002")
  3160. if err != nil {
  3161. log.Fatal("Invalid origin server URL")
  3162. }
  3163. claims, err := getClaims(r.In)
  3164. // q := r.Out.URL.Query()
  3165. r.SetURL(proxyURL)
  3166. // Check if user is logged in, then set or delete the logged_in param
  3167. if claims.Valid() == nil {
  3168. r.Out.Header.Set("X-REMOTE-USER", strconv.Itoa(claims.Id))
  3169. } else {
  3170. r.Out.Header.Del("X-REMOTE-USER")
  3171. }
  3172. }
  3173. func serve() {
  3174. files := http.FileServer(http.Dir(""))
  3175. proxy := &httputil.ReverseProxy{
  3176. Rewrite: setupProxy,
  3177. }
  3178. http.Handle("/assets/", files)
  3179. http.HandleFunc("/api/", api)
  3180. http.Handle("/", proxy)
  3181. log.Fatal(http.ListenAndServe(address, nil))
  3182. }
  3183. func dbReset(db *sql.DB) {
  3184. b, err := os.ReadFile("migrations/reset.sql")
  3185. if err != nil {
  3186. log.Fatal(err)
  3187. }
  3188. _, err = db.Exec(string(b))
  3189. if err != nil {
  3190. log.Fatal(err)
  3191. }
  3192. b, err = os.ReadFile("migrations/0_29092022_setup_tables.sql")
  3193. if err != nil {
  3194. log.Fatal(err)
  3195. }
  3196. _, err = db.Exec(string(b))
  3197. if err != nil {
  3198. log.Fatal(err)
  3199. }
  3200. }
  3201. func generateFees(loan Loan) []Fee {
  3202. var fees []Fee
  3203. var fee Fee
  3204. p := gofakeit.Float32Range(0.5, 10)
  3205. size := gofakeit.Number(1, 10)
  3206. for f := 0; f < size; f++ {
  3207. fee = Fee{
  3208. Amount: int(float32(loan.Amount) * p / 100),
  3209. Perc: p,
  3210. Name: gofakeit.BuzzWord(),
  3211. Type: feeTypes[gofakeit.Number(0, len(feeTypes)-1)],
  3212. }
  3213. fees = append(fees, fee)
  3214. }
  3215. return fees
  3216. }
  3217. func generateCredits(loan Loan) []Fee {
  3218. var fees []Fee
  3219. var fee Fee
  3220. p := gofakeit.Float32Range(-10, -0.5)
  3221. size := gofakeit.Number(1, 10)
  3222. for f := 0; f < size; f++ {
  3223. fee = Fee{
  3224. Amount: int(float32(loan.Amount) * p / 100),
  3225. Perc: p,
  3226. Name: gofakeit.BuzzWord(),
  3227. Type: feeTypes[gofakeit.Number(0, len(feeTypes)-1)],
  3228. }
  3229. fees = append(fees, fee)
  3230. }
  3231. return fees
  3232. }
  3233. func seedAddresses(db *sql.DB) []Address {
  3234. addresses := make([]Address, 10)
  3235. for i, a := range addresses {
  3236. a.Street = gofakeit.Street()
  3237. a.City = gofakeit.City()
  3238. a.Region = gofakeit.State()
  3239. a.Country = "Canada"
  3240. a.Full = fmt.Sprintf("%s, %s %s", a.Street, a.City, a.Region)
  3241. id, err := insertAddress(db, a)
  3242. if err != nil {
  3243. log.Println(err)
  3244. break
  3245. }
  3246. addresses[i].Id = id
  3247. }
  3248. return addresses
  3249. }
  3250. func seedBranches(db *sql.DB, addresses []Address) []Branch {
  3251. branches := make([]Branch, 4)
  3252. for i := range branches {
  3253. branches[i].Name = gofakeit.Company()
  3254. branches[i].Type = "NMLS"
  3255. branches[i].Letterhead = gofakeit.ImagePng(400, 200)
  3256. branches[i].Num = gofakeit.HexUint8()
  3257. branches[i].Phone = gofakeit.Phone()
  3258. branches[i].Address.Id = gofakeit.Number(1, 5)
  3259. id, err := insertBranch(db, branches[i])
  3260. if err != nil {
  3261. log.Println(err)
  3262. break
  3263. }
  3264. branches[i].Id = id
  3265. }
  3266. return branches
  3267. }
  3268. func seedUsers(db *sql.DB, addresses []Address, branches []Branch) []User {
  3269. users := make([]User, 10)
  3270. for i := range users {
  3271. p := gofakeit.Person()
  3272. users[i].FirstName = p.FirstName
  3273. users[i].LastName = p.LastName
  3274. users[i].Email = p.Contact.Email
  3275. users[i].Phone = p.Contact.Phone
  3276. users[i].Branch = branches[gofakeit.Number(0, 3)]
  3277. users[i].Address = addresses[gofakeit.Number(1, 9)]
  3278. // users[i].Letterhead = gofakeit.ImagePng(400, 200)
  3279. // users[i].Avatar = gofakeit.ImagePng(200, 200)
  3280. users[i].Country = []string{"Canada", "USA"}[gofakeit.Number(0, 1)]
  3281. users[i].Password = "test123"
  3282. users[i].Verified = true
  3283. users[i].Title = "Loan Officer"
  3284. users[i].Status = "Subscriber"
  3285. users[i].Role = "User"
  3286. }
  3287. users[0].Email = "test@example.com"
  3288. users[0].Email = "test@example.com"
  3289. users[1].Email = "test2@example.com"
  3290. users[1].Status = "Branch"
  3291. users[1].Role = "Manager"
  3292. users[2].Email = "test3@example.com"
  3293. users[2].Status = "Free"
  3294. users[2].Role = "Admin"
  3295. for i := range users {
  3296. var err error
  3297. users[i].Id, err = insertUser(db, users[i])
  3298. if err != nil {
  3299. log.Println(err)
  3300. break
  3301. }
  3302. }
  3303. return users
  3304. }
  3305. func seedLicenses(db *sql.DB, users []User) []License {
  3306. licenses := make([]License, len(users))
  3307. for i := range licenses {
  3308. licenses[i].UserId = users[i].Id
  3309. licenses[i].Type = []string{"NMLS", "FSRA"}[gofakeit.Number(0, 1)]
  3310. licenses[i].Num = gofakeit.UUID()
  3311. id, err := insertLicense(db, licenses[i])
  3312. if err != nil {
  3313. log.Println(err)
  3314. break
  3315. }
  3316. licenses[i].Id = id
  3317. }
  3318. return licenses
  3319. }
  3320. func seedLoanTypes(db *sql.DB) []LoanType {
  3321. var loantypes []LoanType
  3322. var loantype LoanType
  3323. var err error
  3324. loantype = LoanType{Branch: 0, User: 0, Name: "Conventional"}
  3325. loantype.Id, err = insertLoanType(db, loantype)
  3326. if err != nil {
  3327. panic(err)
  3328. }
  3329. loantypes = append(loantypes, loantype)
  3330. loantype = LoanType{Branch: 0, User: 0, Name: "FHA"}
  3331. loantype.Id, err = insertLoanType(db, loantype)
  3332. if err != nil {
  3333. panic(err)
  3334. }
  3335. loantypes = append(loantypes, loantype)
  3336. loantype = LoanType{Branch: 0, User: 0, Name: "USDA"}
  3337. loantype.Id, err = insertLoanType(db, loantype)
  3338. if err != nil {
  3339. panic(err)
  3340. }
  3341. loantypes = append(loantypes, loantype)
  3342. loantype = LoanType{Branch: 0, User: 0, Name: "VA"}
  3343. loantype.Id, err = insertLoanType(db, loantype)
  3344. if err != nil {
  3345. panic(err)
  3346. }
  3347. loantypes = append(loantypes, loantype)
  3348. return loantypes
  3349. }
  3350. func seedEstimates(db *sql.DB, users []User, ltypes []LoanType) []Estimate {
  3351. var estimates []Estimate
  3352. var estimate Estimate
  3353. var l Loan
  3354. var err error
  3355. for i := 0; i < 15; i++ {
  3356. estimate = Estimate{}
  3357. estimate.User = users[gofakeit.Number(0, len(users)-1)].Id
  3358. estimate.Borrower = Borrower{
  3359. Credit: gofakeit.Number(600, 800),
  3360. Income: gofakeit.Number(1000000, 15000000),
  3361. Num: gofakeit.Number(1, 20),
  3362. }
  3363. estimate.Transaction = []string{"Purchase", "Refinance"}[gofakeit.Number(0, 1)]
  3364. estimate.Price = gofakeit.Number(50000, 200000000)
  3365. estimate.Property =
  3366. propertyTypes[gofakeit.Number(0, len(propertyTypes)-1)]
  3367. estimate.Occupancy =
  3368. []string{"Primary", "Secondary", "Investment"}[gofakeit.Number(0, 2)]
  3369. estimate.Zip = gofakeit.Zip()
  3370. lsize := gofakeit.Number(1, 6)
  3371. for j := 0; j < lsize; j++ {
  3372. l.Type = ltypes[gofakeit.Number(0, len(ltypes)-1)]
  3373. l.Amount = gofakeit.Number(
  3374. int(float32(estimate.Price)*0.5),
  3375. int(float32(estimate.Price)*0.93))
  3376. l.Term = gofakeit.Number(4, 30)
  3377. l.Hoi = gofakeit.Number(50000, 700000)
  3378. l.Hazard = gofakeit.Number(5000, 200000)
  3379. l.Tax = gofakeit.Number(5000, 200000)
  3380. l.Interest = gofakeit.Float32Range(0.5, 8)
  3381. l.Fees = generateFees(l)
  3382. l.Credits = generateCredits(l)
  3383. l.Name = gofakeit.AdjectiveDescriptive()
  3384. estimate.Loans = append(estimate.Loans, l)
  3385. }
  3386. estimates = append(estimates, estimate)
  3387. }
  3388. estimates[0].User = users[0].Id
  3389. estimates[1].User = users[0].Id
  3390. for i := range estimates {
  3391. err = estimates[i].insertEstimate(db)
  3392. if err != nil {
  3393. log.Println(err)
  3394. return estimates
  3395. }
  3396. }
  3397. return estimates
  3398. }
  3399. func seedResults(db *sql.DB, estimates []Estimate) error {
  3400. var err error
  3401. for i := range estimates {
  3402. estimates[i].makeResults()
  3403. err = estimates[i].insertResults(db)
  3404. if err != nil {
  3405. log.Println(err)
  3406. return err
  3407. }
  3408. }
  3409. return nil
  3410. }
  3411. func dbSeed(db *sql.DB) {
  3412. addresses := seedAddresses(db)
  3413. branches := seedBranches(db, addresses)
  3414. users := seedUsers(db, addresses, branches)
  3415. _ = seedLicenses(db, users)
  3416. loantypes := seedLoanTypes(db)
  3417. estimates := seedEstimates(db, users, loantypes)
  3418. _ = seedResults(db, estimates)
  3419. }
  3420. func dev(args []string) {
  3421. os.Setenv("DB_NAME", "skouter_dev")
  3422. os.Setenv("DB_USER", "tester")
  3423. os.Setenv("DB_PASSWORD", "test123")
  3424. stripe.Key = os.Getenv("STRIPE_SECRET_KEY")
  3425. standardPriceId = "price_1OZLK9BPMoXn2pf9kuTAf8rs"
  3426. hookKeys = HookKeys{
  3427. InvoicePaid: os.Getenv("DEV_WEBHOOK_KEY"),
  3428. InvoiceFailed: os.Getenv("DEV_WEBHOOK_KEY"),
  3429. SubCreated: os.Getenv("DEV_WEBHOOK_KEY"),
  3430. SubUpdated: os.Getenv("DEV_WEBHOOK_KEY"),
  3431. SubDeleted: os.Getenv("DEV_WEBHOOK_KEY"),
  3432. }
  3433. db, err := sql.Open("mysql",
  3434. fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?multiStatements=true",
  3435. os.Getenv("DB_USER"),
  3436. os.Getenv("DB_PASSWORD"),
  3437. os.Getenv("DB_NAME"),
  3438. ))
  3439. err = db.Ping()
  3440. if err != nil {
  3441. log.Println("Bad database configuration: %v", err)
  3442. panic(err)
  3443. // maybe os.Exit(1) instead
  3444. }
  3445. if len(args) == 0 {
  3446. serve()
  3447. return
  3448. }
  3449. switch args[0] {
  3450. case "seed":
  3451. dbSeed(db)
  3452. case "reset":
  3453. dbReset(db)
  3454. default:
  3455. return
  3456. }
  3457. db.Close()
  3458. }
  3459. func check(args []string) {
  3460. os.Setenv("DB_NAME", "skouter_dev")
  3461. os.Setenv("DB_USER", "tester")
  3462. os.Setenv("DB_PASSWORD", "test123")
  3463. files := http.FileServer(http.Dir(""))
  3464. http.Handle("/assets/", files)
  3465. http.HandleFunc("/", checkPdf)
  3466. log.Fatal(http.ListenAndServe(address, nil))
  3467. }
  3468. func main() {
  3469. if len(os.Args) <= 1 {
  3470. serve()
  3471. return
  3472. }
  3473. switch os.Args[1] {
  3474. case "dev":
  3475. dev(os.Args[2:])
  3476. case "checkpdf":
  3477. check(os.Args[2:])
  3478. default:
  3479. return
  3480. }
  3481. }