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

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